瀏覽代碼

整合HTEXLib

CrazyIter 4 年之前
父節點
當前提交
2146530776
共有 85 個文件被更改,包括 24 次插入81983 次删除
  1. 0 1
      TEAMModelOS.SDK/DI/AzureCosmos/AzureCosmosFactory.cs
  2. 0 601
      TEAMModelOS.SDK/Module/OpenXmlTool/ChartUpdater.cs
  3. 0 36
      TEAMModelOS.SDK/Module/OpenXmlTool/ColorParser.cs
  4. 0 67
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/ComparisonUnit.cs
  5. 0 215
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/ComparisonUnitAtom.cs
  6. 0 77
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/ComparisonUnitGroup.cs
  7. 0 14
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/ComparisonUnitGroupType.cs
  8. 0 81
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/ComparisonUnitWord.cs
  9. 0 70
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/CorrelatedSequence.cs
  10. 0 16
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/CorrelationStatus.cs
  11. 0 15
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/PartSHA1HashAnnotation.cs
  12. 0 12
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WithHierarchicalGroupingKey.cs
  13. 0 401
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Internal.Methods.ComparisonUnits.cs
  14. 0 276
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.Fields.cs
  15. 0 328
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.Methods.Hashing.cs
  16. 0 1326
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.Methods.Lcs.cs
  17. 0 331
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.Methods.PreProcessMarkup.cs
  18. 0 3232
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.Methods.ProduceDocument.cs
  19. 0 103
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.Methods.Util.cs
  20. 0 36
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.NestedTypes.cs
  21. 0 227
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Public.Methods.Compare.cs
  22. 0 1002
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Public.Methods.Consolidate.cs
  23. 0 214
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Public.Methods.GetRevisions.cs
  24. 0 29
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Public.NestedTypes.cs
  25. 0 10
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparerConsolidateSettings.cs
  26. 0 27
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparerExtensions.cs
  27. 0 29
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparerSettings.cs
  28. 0 59
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparerUtil.cs
  29. 0 14
      TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlRevisedDocumentInfo.cs
  30. 0 857
      TEAMModelOS.SDK/Module/OpenXmlTool/DocumentAssembler.cs
  31. 0 4038
      TEAMModelOS.SDK/Module/OpenXmlTool/DocumentBuilder.cs
  32. 0 833
      TEAMModelOS.SDK/Module/OpenXmlTool/ExcelFormula.cs
  33. 0 416
      TEAMModelOS.SDK/Module/OpenXmlTool/FieldRetriever.cs
  34. 0 3510
      TEAMModelOS.SDK/Module/OpenXmlTool/FormattingAssembler.cs
  35. 0 240
      TEAMModelOS.SDK/Module/OpenXmlTool/GetListItemText_Default.cs
  36. 0 233
      TEAMModelOS.SDK/Module/OpenXmlTool/GetListItemText_fr_FR.cs
  37. 0 122
      TEAMModelOS.SDK/Module/OpenXmlTool/GetListItemText_ru_RU.cs
  38. 0 213
      TEAMModelOS.SDK/Module/OpenXmlTool/GetListItemText_sv_SE.cs
  39. 0 218
      TEAMModelOS.SDK/Module/OpenXmlTool/GetListItemText_tr_TR.cs
  40. 0 130
      TEAMModelOS.SDK/Module/OpenXmlTool/GetListItemText_zh_CN.cs
  41. 0 533
      TEAMModelOS.SDK/Module/OpenXmlTool/HtmlToWmlConverter.cs
  42. 0 5359
      TEAMModelOS.SDK/Module/OpenXmlTool/HtmlToWmlConverterCore.cs
  43. 0 3743
      TEAMModelOS.SDK/Module/OpenXmlTool/HtmlToWmlCssApplier.cs
  44. 0 4388
      TEAMModelOS.SDK/Module/OpenXmlTool/HtmlToWmlCssParser.cs
  45. 0 1169
      TEAMModelOS.SDK/Module/OpenXmlTool/ListItemRetriever.cs
  46. 0 692
      TEAMModelOS.SDK/Module/OpenXmlTool/MarkupSimplifier.cs
  47. 0 1071
      TEAMModelOS.SDK/Module/OpenXmlTool/MetricsGetter.cs
  48. 0 562
      TEAMModelOS.SDK/Module/OpenXmlTool/OpenXmlRegex.cs
  49. 0 679
      TEAMModelOS.SDK/Module/OpenXmlTool/OxPtHelpers.cs
  50. 0 2109
      TEAMModelOS.SDK/Module/OpenXmlTool/PegBase.cs
  51. 0 62
      TEAMModelOS.SDK/Module/OpenXmlTool/PowerToolsBlock.cs
  52. 0 70
      TEAMModelOS.SDK/Module/OpenXmlTool/PowerToolsBlockExtensions.cs
  53. 0 1825
      TEAMModelOS.SDK/Module/OpenXmlTool/PresentationBuilder.cs
  54. 0 6
      TEAMModelOS.SDK/Module/OpenXmlTool/Properties/AssemblyInfo.cs
  55. 0 757
      TEAMModelOS.SDK/Module/OpenXmlTool/PtOpenXmlDocument.cs
  56. 0 5957
      TEAMModelOS.SDK/Module/OpenXmlTool/PtOpenXmlUtil.cs
  57. 0 1248
      TEAMModelOS.SDK/Module/OpenXmlTool/PtUtil.cs
  58. 0 639
      TEAMModelOS.SDK/Module/OpenXmlTool/ReferenceAdder.cs
  59. 0 46
      TEAMModelOS.SDK/Module/OpenXmlTool/RevisionAccepter.cs
  60. 0 3237
      TEAMModelOS.SDK/Module/OpenXmlTool/RevisionProcessor.cs
  61. 0 105
      TEAMModelOS.SDK/Module/OpenXmlTool/SSFormula.cs
  62. 0 54
      TEAMModelOS.SDK/Module/OpenXmlTool/ScalarTypes.cs
  63. 0 260
      TEAMModelOS.SDK/Module/OpenXmlTool/SmlCellFormatter.cs
  64. 0 1091
      TEAMModelOS.SDK/Module/OpenXmlTool/SmlDataRetriever.cs
  65. 0 308
      TEAMModelOS.SDK/Module/OpenXmlTool/SmlToHtmlConverter.cs
  66. 0 208
      TEAMModelOS.SDK/Module/OpenXmlTool/SpreadsheetDocumentManager.cs
  67. 0 781
      TEAMModelOS.SDK/Module/OpenXmlTool/SpreadsheetWriter.cs
  68. 0 61
      TEAMModelOS.SDK/Module/OpenXmlTool/StronglyTypedBlock.cs
  69. 0 72
      TEAMModelOS.SDK/Module/OpenXmlTool/TestUtil.cs
  70. 0 428
      TEAMModelOS.SDK/Module/OpenXmlTool/TextReplacer.cs
  71. 0 337
      TEAMModelOS.SDK/Module/OpenXmlTool/UnicodeMapper.cs
  72. 0 106
      TEAMModelOS.SDK/Module/OpenXmlTool/WmlDocument.cs
  73. 0 3428
      TEAMModelOS.SDK/Module/OpenXmlTool/WmlToHtmlConverter.cs
  74. 0 2098
      TEAMModelOS.SDK/Module/OpenXmlTool/WmlToXml.cs
  75. 0 2185
      TEAMModelOS.SDK/Module/OpenXmlTool/WorksheetAccessor.cs
  76. 0 463
      TEAMModelOS.SDK/Module/OpenXmlTool/XlsxTables.cs
  77. 20 54
      TEAMModelOS/Controllers/Exam/ImportExerciseController.cs
  78. 0 24
      TEAMModelOS/Models/Dto/LangConfig.cs
  79. 0 551
      TEAMModelOS/Services/Evaluation/HtmlAnalyzeService.cs
  80. 0 187
      TEAMModelOS/Services/Evaluation/ImportExerciseService.cs
  81. 0 3177
      TEAMModelOS/Services/PowerPoint/HtexService.cs
  82. 0 1072
      TEAMModelOS/Services/PowerPoint/ShapeHelper.cs
  83. 0 11120
      TEAMModelOS/Services/PowerPoint/ShapeSvg.cs
  84. 2 1
      TEAMModelOS/Startup.cs
  85. 2 1
      TEAMModelOS/TEAMModelOS.csproj

+ 0 - 1
TEAMModelOS.SDK/DI/AzureCosmos/AzureCosmosFactory.cs

@@ -13,7 +13,6 @@ using TEAMModelOS.SDK.Context.Attributes.Azure;
 using TEAMModelOS.SDK.Context.Configuration;
 using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
 using TEAMModelOS.SDK.Helper.Common.ReflectorExtensions;
-using OpenXmlPowerTools;
 using System.Diagnostics;
 using System.IO;
 using System.Linq.Expressions;

+ 0 - 601
TEAMModelOS.SDK/Module/OpenXmlTool/ChartUpdater.cs

@@ -1,601 +0,0 @@
-// 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.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-using OpenXmlPowerTools;
-
-namespace OpenXmlPowerTools
-{
-    public enum ChartDataType
-    {
-        Number,
-        String,
-        DateTime,
-    }
-
-    // Format Codes
-    // 0 - general
-    // 1 - 0
-    // 2 - 0.00
-    // 3 - #,##0
-    // 4 - #,##0.00
-    // 9 - 0%
-    // 10 - 0.00%
-    // 11 - 0.00E+00
-    // 12 - # ?/?
-    // 13 - # ??/??
-    // 14 - mm-dd-yy
-    // 15 - d-mmm-yy
-    // 16 - d-mmm
-    // 17 - mmm-yy
-    // 18 - h:mm AM/PM
-    // 19 - h:mm:ss AM/PM
-    // 20 - h:mm
-    // 21 - h:mm:ss
-    // 22 - m/d/yy h:mm
-    // 37 - #,##0 ;(#,##0)
-    // 38 - #,##0 ;[Red](#,##0)
-    // 39 - #,##0.00;(#,##0.00)
-    // 40 - #,##0.00;[Red](#,##0.00)
-    // 45 - mm:ss
-    // 46 - [h]:mm:ss
-    // 47 - mmss.0
-    // 48 - ##0.0E+0
-    // 49 - @
-
-    public class ChartData
-    {
-        public string[] SeriesNames;
-
-        public ChartDataType CategoryDataType;
-        public int CategoryFormatCode;
-        public string[] CategoryNames;
-
-        public double[][] Values;
-    }
-
-    public class ChartUpdater
-    {
-        public static bool UpdateChart(WordprocessingDocument wDoc, string contentControlTag, ChartData chartData)
-        {
-            var mainDocumentPart = wDoc.MainDocumentPart;
-            var mdXDoc = mainDocumentPart.GetXDocument();
-            var cc = mdXDoc.Descendants(W.sdt)
-                .FirstOrDefault(sdt => (string)sdt.Elements(W.sdtPr).Elements(W.tag).Attributes(W.val).FirstOrDefault() == contentControlTag);
-            if (cc != null)
-            {
-                var chartRid = (string)cc.Descendants(C.chart).Attributes(R.id).FirstOrDefault();
-                if (chartRid != null)
-                {
-                    ChartPart chartPart = (ChartPart)mainDocumentPart.GetPartById(chartRid);
-                    UpdateChart(chartPart, chartData);
-                    var newContent = cc.Elements(W.sdtContent).Elements().Select(e => new XElement(e));
-                    cc.ReplaceWith(newContent);
-                    mainDocumentPart.PutXDocument();
-                    return true;
-                }
-            }
-            return false;
-        }
-
-        public static void UpdateChart(ChartPart chartPart, ChartData chartData)
-        {
-            if (chartData.Values.Length != chartData.SeriesNames.Length)
-                throw new ArgumentException("Invalid chart data");
-            foreach (var ser in chartData.Values)
-            {
-                if (ser.Length != chartData.CategoryNames.Length)
-                    throw new ArgumentException("Invalid chart data");
-            }
-
-            UpdateSeries(chartPart, chartData);
-        }
-
-        private static Dictionary<int, string> FormatCodes = new Dictionary<int, string>()
-        {
-            { 0, "general" },
-            { 1, "0" },
-            { 2, "0.00" },
-            { 3, "#,##0" },
-            { 4, "#,##0.00" },
-            { 9, "0%" },
-            { 10, "0.00%" },
-            { 11, "0.00E+00" },
-            { 12, "# ?/?" },
-            { 13, "# ??/??" },
-            { 14, "mm-dd-yy" },
-            { 15, "d-mmm-yy" },
-            { 16, "d-mmm" },
-            { 17, "mmm-yy" },
-            { 18, "h:mm AM/PM" },
-            { 19, "h:mm:ss AM/PM" },
-            { 20, "h:mm" },
-            { 21, "h:mm:ss" },
-            { 22, "m/d/yy h:mm" },
-            { 37, "#,##0 ;(#,##0)" },
-            { 38, "#,##0 ;[Red](#,##0)" },
-            { 39, "#,##0.00;(#,##0.00)" },
-            { 40, "#,##0.00;[Red](#,##0.00)" },
-            { 45, "mm:ss" },
-            { 46, "[h]:mm:ss" },
-            { 47, "mmss.0" },
-            { 48, "##0.0E+0" },
-            { 49, "@" },
-        };
-
-        private static void UpdateSeries(ChartPart chartPart, ChartData chartData)
-        {
-            UpdateEmbeddedWorkbook(chartPart, chartData);
-
-            XDocument cpXDoc = chartPart.GetXDocument();
-            XElement root = cpXDoc.Root;
-            var firstSeries = root.Descendants(C.ser).FirstOrDefault();
-            var numRef = firstSeries.Elements(C.val).Elements(C.numRef).FirstOrDefault();
-            string sheetName = null;
-            var f = (string)firstSeries.Descendants(C.f).FirstOrDefault();
-            if (f != null)
-                sheetName = f.Split('!')[0];
-
-            // remove all but first series
-            XName chartType = firstSeries.Parent.Name;
-            firstSeries.Parent.Elements(C.ser).Skip(1).Remove();
-
-            var newSetOfSeries = chartData.SeriesNames
-                .Select((string sn, int si) =>
-                {
-                    XElement cat = null;
-
-                    var oldCat = firstSeries.Elements(C.cat).FirstOrDefault();
-                    if (oldCat == null)
-                        throw new OpenXmlPowerToolsException("Invalid chart markup");
-
-                    var catHasFormula = oldCat.Descendants(C.f).Any();
-                    if (catHasFormula)
-                    {
-                        XElement newFormula = null;
-                        if (sheetName != null)
-                            newFormula = new XElement(C.f, string.Format("{0}!$A$2:$A${1}", sheetName, chartData.CategoryNames.Length + 1));
-                        if (chartData.CategoryDataType == ChartDataType.String)
-                        {
-                            cat = new XElement(C.cat,
-                                new XElement(C.strRef,
-                                    newFormula,
-                                    new XElement(C.strCache,
-                                        new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)),
-                                        chartData.CategoryNames.Select((string cn, int ci) =>
-                                        {
-                                            var newPt = new XElement(C.pt,
-                                                new XAttribute("idx", ci),
-                                                new XElement(C.v, chartData.CategoryNames[ci]));
-                                            return newPt;
-                                        }))));
-                        }
-                        else
-                        {
-                            cat = new XElement(C.cat,
-                                new XElement(C.numRef,
-                                    newFormula,
-                                    new XElement(C.numCache,
-                                        new XElement(C.formatCode, FormatCodes[chartData.CategoryFormatCode]),
-                                        new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)),
-                                        chartData.CategoryNames.Select((string cn, int ci) =>
-                                        {
-                                            var newPt = new XElement(C.pt,
-                                                new XAttribute("idx", ci),
-                                                new XElement(C.v, chartData.CategoryNames[ci]));
-                                            return newPt;
-                                        }))));
-                        }
-                    }
-                    else
-                    {
-                        if (chartData.CategoryDataType == ChartDataType.String)
-                        {
-                            cat = new XElement(C.cat,
-                                new XElement(C.strLit,
-                                    new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)),
-                                    chartData.CategoryNames.Select((string cn, int ci) =>
-                                    {
-                                        var newPt = new XElement(C.pt,
-                                            new XAttribute("idx", ci),
-                                            new XElement(C.v, chartData.CategoryNames[ci]));
-                                        return newPt;
-                                    })));
-                        }
-                        else
-                        {
-                            cat = new XElement(C.cat,
-                                new XElement(C.numLit,
-                                    new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)),
-                                    chartData.CategoryNames.Select((string cn, int ci) =>
-                                    {
-                                        var newPt = new XElement(C.pt,
-                                            new XAttribute("idx", ci),
-                                            new XElement(C.v, chartData.CategoryNames[ci]));
-                                        return newPt;
-                                    })));
-                        }
-                    }
-
-                    XElement newCval = null;
-
-                    if (sheetName == null)
-                    {
-                        newCval = new XElement(C.val,
-                                new XElement(C.numLit,
-                                    new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)),
-                                    chartData.CategoryNames.Select((string cn, int ci) =>
-                                    {
-                                        var newPt = new XElement(C.pt,
-                                            new XAttribute("idx", ci),
-                                            new XElement(C.v, chartData.Values[si][ci]));
-                                        return newPt;
-                                    })));
-                    }
-                    else
-                    {
-                        newCval = new XElement(C.val,
-                                new XElement(C.numRef,
-                                    sheetName != null ?
-                                        new XElement(C.f, string.Format("{0}!${2}$2:${2}${1}", sheetName, chartData.CategoryNames.Length + 1, SpreadsheetMLUtil.IntToColumnId(si + 1))) : null,
-                                    new XElement(C.numCache,
-                                        sheetName != null ? numRef.Descendants(C.formatCode) : null,
-                                        new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)),
-                                        chartData.CategoryNames.Select((string cn, int ci) =>
-                                        {
-                                            var newPt = new XElement(C.pt,
-                                                new XAttribute("idx", ci),
-                                                new XElement(C.v, chartData.Values[si][ci]));
-                                            return newPt;
-                                        }))));
-                    }
-
-                    var serHasFormula = firstSeries.Descendants(C.f).Any();
-                    XElement tx = null;
-                    if (serHasFormula)
-                    {
-                        XElement newFormula = null;
-                        if (sheetName != null)
-                            newFormula = new XElement(C.f, string.Format("{0}!${1}$1", sheetName, SpreadsheetMLUtil.IntToColumnId(si + 1)));
-                        tx = new XElement(C.tx,
-                            new XElement(C.strRef,
-                                newFormula,
-                                new XElement(C.strCache,
-                                    new XElement(C.ptCount, new XAttribute("val", 1)),
-                                    new XElement(C.pt,
-                                        new XAttribute("idx", 0),
-                                        new XElement(C.v, chartData.SeriesNames[si])))));
-                    }
-                    else
-                    {
-                        tx = new XElement(C.tx,
-                            new XElement(C.v, chartData.SeriesNames[si]));
-                    }
-
-                    XElement newSer = null;
-
-                    if (chartType == C.area3DChart || chartType == C.areaChart)
-                    {
-                        newSer = new XElement(C.ser,
-                            // common
-                            new XElement(C.idx, new XAttribute("val", si)),
-                            new XElement(C.order, new XAttribute("val", si)),
-                            tx,
-                            firstSeries.Elements(C.spPr),
-
-                            // CT_AreaSer
-                            firstSeries.Elements(C.pictureOptions),
-                            firstSeries.Elements(C.dPt),
-                            firstSeries.Elements(C.dLbls),
-                            firstSeries.Elements(C.trendline),
-                            firstSeries.Elements(C.errBars),
-                            cat,
-                            newCval,
-                            firstSeries.Elements(C.extLst));
-                    }
-                    else if (chartType == C.bar3DChart || chartType == C.barChart)
-                    {
-                        newSer = new XElement(C.ser,
-                            // common
-                            new XElement(C.idx, new XAttribute("val", si)),
-                            new XElement(C.order, new XAttribute("val", si)),
-                            tx,
-                            firstSeries.Elements(C.spPr),
-
-                            // CT_BarSer
-                            firstSeries.Elements(C.invertIfNegative),
-                            firstSeries.Elements(C.pictureOptions),
-                            firstSeries.Elements(C.dPt),
-                            firstSeries.Elements(C.dLbls),
-                            firstSeries.Elements(C.trendline),
-                            firstSeries.Elements(C.errBars),
-                            cat,
-                            newCval,
-                            firstSeries.Elements(C.shape),
-                            firstSeries.Elements(C.extLst));
-                    }
-                    else if (chartType == C.line3DChart || chartType == C.lineChart || chartType == C.stockChart)
-                    {
-                        newSer = new XElement(C.ser,
-                            // common
-                            new XElement(C.idx, new XAttribute("val", si)),
-                            new XElement(C.order, new XAttribute("val", si)),
-                            tx,
-                            firstSeries.Elements(C.spPr),
-
-                            // CT_LineSer
-                            firstSeries.Elements(C.marker),
-                            firstSeries.Elements(C.dPt),
-                            firstSeries.Elements(C.dLbls),
-                            firstSeries.Elements(C.trendline),
-                            firstSeries.Elements(C.errBars),
-                            cat,
-                            newCval,
-                            firstSeries.Elements(C.smooth),
-                            firstSeries.Elements(C.extLst));
-                    }
-                    else if (chartType == C.doughnutChart || chartType == C.ofPieChart || chartType == C.pie3DChart || chartType == C.pieChart)
-                    {
-                        newSer = new XElement(C.ser,
-                            // common
-                            new XElement(C.idx, new XAttribute("val", si)),
-                            new XElement(C.order, new XAttribute("val", si)),
-                            tx,
-                            firstSeries.Elements(C.spPr),
-
-                            // CT_PieSer
-                            firstSeries.Elements(C.explosion),
-                            firstSeries.Elements(C.dPt),
-                            firstSeries.Elements(C.dLbls),
-                            cat,
-                            newCval,
-                            firstSeries.Elements(C.extLst));
-                    }
-                    else if (chartType == C.surface3DChart || chartType == C.surfaceChart)
-                    {
-                        newSer = new XElement(C.ser,
-                            // common
-                            new XElement(C.idx, new XAttribute("val", si)),
-                            new XElement(C.order, new XAttribute("val", si)),
-                            tx,
-                            firstSeries.Elements(C.spPr),
-
-                            // CT_SurfaceSer
-                            cat,
-                            newCval,
-                            firstSeries.Elements(C.extLst));
-                    }
-
-                    if (newSer == null)
-                        throw new OpenXmlPowerToolsException("Unsupported chart type");
-
-                    int accentNumber = (si % 6) + 1;
-                    newSer = (XElement)UpdateAccentTransform(newSer, accentNumber);
-                    return newSer;
-                });
-            firstSeries.ReplaceWith(newSetOfSeries);
-            chartPart.PutXDocument();
-        }
-
-        private static void UpdateEmbeddedWorkbook(ChartPart chartPart, ChartData chartData)
-        {
-            XDocument cpXDoc = chartPart.GetXDocument();
-            XElement root = cpXDoc.Root;
-            var firstSeries = root.Descendants(C.ser).FirstOrDefault();
-            if (firstSeries == null)
-                return;
-            var firstFormula = (string)firstSeries.Descendants(C.f).FirstOrDefault();
-            if (firstFormula == null)
-                return;
-            var sheet = firstFormula.Split('!')[0];
-            var embeddedSpreadsheetRid = (string)root.Descendants(C.externalData).Attributes(R.id).FirstOrDefault();
-            if (embeddedSpreadsheetRid == null)
-                return;
-            var embeddedSpreadsheet = chartPart.GetPartById(embeddedSpreadsheetRid);
-            if (embeddedSpreadsheet != null)
-            {
-                using (SpreadsheetDocument sDoc = SpreadsheetDocument.Open(embeddedSpreadsheet.GetStream(), true))
-                {
-                    var workbookPart = sDoc.WorkbookPart;
-                    var wbRoot = workbookPart.GetXDocument().Root;
-                    var sheetRid = (string)wbRoot
-                        .Elements(S.sheets)
-                        .Elements(S.sheet)
-                        .Where(s => (string)s.Attribute("name") == sheet)
-                        .Attributes(R.id)
-                        .FirstOrDefault();
-                    if (sheetRid != null)
-                    {
-                        var sheetPart = workbookPart.GetPartById(sheetRid);
-                        var xdSheet = sheetPart.GetXDocument();
-                        var sheetData = xdSheet.Descendants(S.sheetData).FirstOrDefault();
-
-                        var stylePart = workbookPart.WorkbookStylesPart;
-                        var xdStyle = stylePart.GetXDocument();
-
-                        int categoryStyleId = 0;
-                        if (chartData.CategoryFormatCode != 0)
-                            categoryStyleId = AddDxfToDxfs(xdSheet, xdStyle, chartData.CategoryFormatCode);
-                        stylePart.PutXDocument();
-
-                        var firstRow = new XElement(S.row,
-                            new XAttribute("r", "1"),
-                            new XAttribute("spans", string.Format("1:{0}", chartData.SeriesNames.Length + 1)),
-                            new [] { new XElement(S.c,
-                                new XAttribute("r", "A1"),
-                                new XAttribute("t", "str"),
-                                new XElement(S.v,
-                                    new XAttribute(XNamespace.Xml + "space", "preserve"),
-                                    " "))}
-                                .Concat(
-                                    chartData.SeriesNames
-                                        .Select((sn, i) => new XElement(S.c,
-                                            new XAttribute("r", RowColToString(0, i + 1)),
-                                            new XAttribute("t", "str"),
-                                            new XElement(S.v, sn)))));
-                        var otherRows = chartData
-                            .CategoryNames
-                            .Select((cn, r) =>
-                            {
-                                var row = new XElement(S.row,
-                                    new XAttribute("r", r + 2),
-                                    new XAttribute("spans", string.Format("1:{0}", chartData.SeriesNames.Length + 1)),
-                                    new[] {
-                                        new XElement(S.c,
-                                            new XAttribute("r", RowColToString(r + 1, 0)),
-                                            categoryStyleId != 0 ? new XAttribute("s", categoryStyleId) : null,
-                                            chartData.CategoryDataType == ChartDataType.String ? new XAttribute("t", "str") : null,
-                                            new XElement(S.v, cn))
-                                    }.Concat(
-                                        Enumerable.Range(0, chartData.Values.Length)
-                                            .Select((c, ci) =>
-                                            {
-                                                var cell = new XElement(S.c,
-                                                    new XAttribute("r", RowColToString(r + 1, ci + 1)),
-                                                    new XElement(S.v, chartData.Values[ci][r]));
-                                                return cell;
-                                            })));
-                                return row;
-                            });
-                        var allRows = new[] {
-                            firstRow
-                        }.Concat(otherRows);
-                        var newSheetData = new XElement(S.sheetData,
-                            allRows);
-                        sheetData.ReplaceWith(newSheetData);
-                        sheetPart.PutXDocument();
-
-                        var tablePartRid = (string)xdSheet
-                            .Root
-                            .Elements(S.tableParts)
-                            .Elements(S.tablePart)
-                            .Attributes(R.id)
-                            .FirstOrDefault();
-                        if (tablePartRid != null)
-                        {
-                            var partTable = sheetPart.GetPartById(tablePartRid);
-                            var xdTablePart = partTable.GetXDocument();
-                            var xaRef = xdTablePart.Root.Attribute("ref");
-                            xaRef.Value = string.Format("A1:{0}", RowColToString(chartData.CategoryNames.Length - 1, chartData.SeriesNames.Length));
-                            var xeNewTableColumns = new XElement(S.tableColumns,
-                                new XAttribute("count", chartData.SeriesNames.Count() + 1),
-                                new[] {
-                                    new XElement(S.tableColumn,
-                                        new XAttribute("id", 1),
-                                        new XAttribute("name", " "))
-                                }.Concat(
-                                    chartData.SeriesNames.Select((cn, ci) =>
-                                        new XElement(S.tableColumn,
-                                            new XAttribute("id", ci + 2),
-                                            new XAttribute("name", cn)))));
-                            var xeExistingTableColumns = xdTablePart.Root.Element(S.tableColumns);
-                            if (xeExistingTableColumns != null)
-                                xeExistingTableColumns.ReplaceWith(xeNewTableColumns);
-                            partTable.PutXDocument();
-                        }
-                    }
-                }
-            }
-        }
-
-        private static int AddDxfToDxfs(XDocument xdSheet, XDocument xdStyle, int formatCodeToAdd)
-        {
-            // add xf to cellXfs
-            var cellXfs = xdStyle
-                .Root
-                .Element(S.cellXfs);
-            if (cellXfs == null)
-            {
-                var cellStyleXfs = xdStyle
-                    .Root
-                    .Element(S.cellStyleXfs);
-                if (cellStyleXfs != null)
-                {
-                    cellStyleXfs.AddAfterSelf(
-                        new XElement(S.cellXfs,
-                            new XAttribute("count", 0)));
-                    cellXfs = xdSheet
-                        .Root
-                        .Element(S.cellXfs);
-                }
-            }
-            if (cellXfs == null)
-            {
-                var borders = xdStyle
-                    .Root
-                    .Element(S.borders);
-                if (borders != null)
-                {
-                    borders.AddAfterSelf(
-                        new XElement(S.cellXfs,
-                            new XAttribute("count", 0)));
-                    cellXfs = xdSheet
-                        .Root
-                        .Element(S.cellXfs);
-                }
-            }
-            if (cellXfs == null)
-                throw new OpenXmlPowerToolsException("Internal error");
-
-            var cnt = (int)cellXfs.Attribute("count");
-            cnt++;
-            cellXfs.Attribute("count").Value = cnt.ToString();
-            cellXfs.Add(
-                new XElement(S.xf,
-                    new XAttribute("numFmtId", formatCodeToAdd),
-                    new XAttribute("fontId", 0),
-                    new XAttribute("fillId", 0),
-                    new XAttribute("borderId", 0),
-                    new XAttribute("applyNumberFormat", 1)));
-            return cnt - 1;
-        }
-
-        private static string RowColToString(int row, int col)
-        {
-            var str = SpreadsheetMLUtil.IntToColumnId(col) + (row + 1).ToString();
-            return str;
-        }
-
-        private static object UpdateAccentTransform(XNode node, int accentNumber)
-        {
-            if (node is XElement element)
-            {
-                if (element.Name == A.schemeClr && (string)element.Attribute("val") == "accent1")
-                    return new XElement(A.schemeClr, new XAttribute("val", "accent" + accentNumber));
-
-                return new XElement(element.Name,
-                    element.Attributes(),
-                    element.Nodes().Select(n => UpdateAccentTransform(n, accentNumber)));
-            }
-            return node;
-        }
-
-        public static bool UpdateChart(PresentationDocument pDoc, int slideNumber, ChartData chartData)
-        {
-            var presentationPart = pDoc.PresentationPart;
-            var pXDoc = presentationPart.GetXDocument();
-            var sldIdElement = pXDoc.Root.Elements(P.sldIdLst).Elements(P.sldId).Skip(slideNumber - 1).FirstOrDefault();
-            if (sldIdElement != null)
-            {
-                var rId = (string)sldIdElement.Attribute(R.id);
-                var slidePart = presentationPart.GetPartById(rId);
-                var sXDoc = slidePart.GetXDocument();
-                var chartRid = (string)sXDoc.Descendants(C.chart).Attributes(R.id).FirstOrDefault();
-                if (chartRid != null)
-                {
-                    ChartPart chartPart = (ChartPart)slidePart.GetPartById(chartRid);
-                    UpdateChart(chartPart, chartData);
-                    return true;
-                }
-                return true;
-            }
-            return false;
-        }
-    }
-}

+ 0 - 36
TEAMModelOS.SDK/Module/OpenXmlTool/ColorParser.cs

@@ -1,36 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-using System.Drawing;
-
-namespace OpenXmlPowerTools
-{
-    public static class ColorParser
-    {
-        public static Color FromName(string name)
-        {
-            return Color.FromName(name);
-        }
-
-        public static bool TryFromName(string name, out Color color)
-        {
-            try
-            {
-                color = Color.FromName(name);
-
-                return color.IsNamedColor;
-            }
-            catch
-            {
-                color = default(Color);
-
-                return false;
-            }
-        }
-
-        public static bool IsValidName(string name)
-        {
-            return TryFromName(name, out _);
-        }
-    }
-}

+ 0 - 67
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/ComparisonUnit.cs

@@ -1,67 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text;
-
-namespace OpenXmlPowerTools
-{
-    public abstract class ComparisonUnit
-    {
-        private int? _descendantContentAtomsCount;
-
-        public CorrelationStatus CorrelationStatus { get; set; }
-
-        public List<ComparisonUnit> Contents { get; protected set; }
-
-        public string SHA1Hash { get; protected set; }
-
-        public int DescendantContentAtomsCount
-        {
-            get
-            {
-                if (_descendantContentAtomsCount != null) return (int) _descendantContentAtomsCount;
-
-                _descendantContentAtomsCount = DescendantContentAtoms().Count();
-                return (int) _descendantContentAtomsCount;
-            }
-        }
-
-        private IEnumerable<ComparisonUnit> Descendants()
-        {
-            var comparisonUnitList = new List<ComparisonUnit>();
-            DescendantsInternal(this, comparisonUnitList);
-            return comparisonUnitList;
-        }
-
-        public IEnumerable<ComparisonUnitAtom> DescendantContentAtoms()
-        {
-            return Descendants().OfType<ComparisonUnitAtom>();
-        }
-
-        private static void DescendantsInternal(
-            ComparisonUnit comparisonUnit,
-            List<ComparisonUnit> comparisonUnitList)
-        {
-            foreach (ComparisonUnit cu in comparisonUnit.Contents)
-            {
-                comparisonUnitList.Add(cu);
-                if (cu.Contents != null && cu.Contents.Any())
-                    DescendantsInternal(cu, comparisonUnitList);
-            }
-        }
-
-        public abstract string ToString(int indent);
-
-        internal static string ComparisonUnitListToString(ComparisonUnit[] cul)
-        {
-            var sb = new StringBuilder();
-            sb.Append("Dump Comparision Unit List To String" + Environment.NewLine);
-            foreach (ComparisonUnit item in cul) sb.Append(item.ToString(2) + Environment.NewLine);
-
-            return sb.ToString();
-        }
-    }
-}

+ 0 - 215
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/ComparisonUnitAtom.cs

@@ -1,215 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public class ComparisonUnitAtom : ComparisonUnit
-    {
-        public ComparisonUnitAtom(
-            XElement contentElement,
-            XElement[] ancestorElements,
-            OpenXmlPart part,
-            WmlComparerSettings settings)
-        {
-            ContentElement = contentElement;
-            AncestorElements = ancestorElements;
-            Part = part;
-            RevTrackElement = GetRevisionTrackingElementFromAncestors(contentElement, AncestorElements);
-
-            if (RevTrackElement == null)
-            {
-                CorrelationStatus = CorrelationStatus.Equal;
-            }
-            else
-            {
-                if (RevTrackElement.Name == W.del)
-                {
-                    CorrelationStatus = CorrelationStatus.Deleted;
-                }
-                else if (RevTrackElement.Name == W.ins)
-                {
-                    CorrelationStatus = CorrelationStatus.Inserted;
-                }
-            }
-
-            var sha1Hash = (string) contentElement.Attribute(PtOpenXml.SHA1Hash);
-            if (sha1Hash != null)
-            {
-                SHA1Hash = sha1Hash;
-            }
-            else
-            {
-                string shaHashString = GetSha1HashStringForElement(ContentElement, settings);
-                SHA1Hash = WmlComparerUtil.SHA1HashStringForUTF8String(shaHashString);
-            }
-        }
-
-        // AncestorElements are kept in order from the body to the leaf, because this is the order in which we need to access in order
-        // to reassemble the document.  However, in many places in the code, it is necessary to find the nearest ancestor, i.e. cell
-        // so it is necessary to reverse the order when looking for it, i.e. look from the leaf back to the body element.
-
-        public XElement[] AncestorElements { get; }
-
-        public XElement ContentElement { get; }
-
-        public XElement RevTrackElement { get; }
-
-        public string[] AncestorUnids { get; set; }
-
-        public ComparisonUnitAtom ComparisonUnitAtomBefore { get; set; }
-
-        public XElement ContentElementBefore { get; set; }
-
-        public OpenXmlPart Part { get; }
-
-        private static string GetSha1HashStringForElement(XElement contentElement, WmlComparerSettings settings)
-        {
-            string text = contentElement.Value;
-            if (settings.CaseInsensitive)
-            {
-                text = text.ToUpper(settings.CultureInfo);
-            }
-
-            return contentElement.Name.LocalName + text;
-        }
-
-        private static XElement GetRevisionTrackingElementFromAncestors(
-            XElement contentElement,
-            IEnumerable<XElement> ancestors)
-        {
-            return contentElement.Name == W.pPr
-                ? contentElement.Elements(W.rPr).Elements().FirstOrDefault(e => e.Name == W.del || e.Name == W.ins)
-                : ancestors.FirstOrDefault(a => a.Name == W.del || a.Name == W.ins);
-        }
-
-        public override string ToString()
-        {
-            return ToString(0);
-        }
-
-        public override string ToString(int indent)
-        {
-            const int xNamePad = 16;
-            string indentString = "".PadRight(indent);
-
-            var sb = new StringBuilder();
-            sb.Append(indentString);
-
-            var correlationStatus = "";
-            if (CorrelationStatus != CorrelationStatus.Nil)
-            {
-                correlationStatus = $"[{CorrelationStatus.ToString().PadRight(8)}] ";
-            }
-
-            if (ContentElement.Name == W.t || ContentElement.Name == W.delText)
-            {
-                sb.AppendFormat(
-                    "Atom {0}: {1} {2} SHA1:{3} ",
-                    PadLocalName(xNamePad, this),
-                    ContentElement.Value,
-                    correlationStatus,
-                    SHA1Hash.Substring(0, 8));
-
-                AppendAncestorsDump(sb, this);
-            }
-            else
-            {
-                sb.AppendFormat(
-                    "Atom {0}:   {1} SHA1:{2} ",
-                    PadLocalName(xNamePad, this),
-                    correlationStatus,
-                    SHA1Hash.Substring(0, 8));
-
-                AppendAncestorsDump(sb, this);
-            }
-
-            return sb.ToString();
-        }
-
-        public string ToStringAncestorUnids()
-        {
-            return ToStringAncestorUnids(0);
-        }
-
-        private string ToStringAncestorUnids(int indent)
-        {
-            const int xNamePad = 16;
-            string indentString = "".PadRight(indent);
-
-            var sb = new StringBuilder();
-            sb.Append(indentString);
-
-            var correlationStatus = "";
-            if (CorrelationStatus != CorrelationStatus.Nil)
-            {
-                correlationStatus = $"[{CorrelationStatus.ToString().PadRight(8)}] ";
-            }
-
-            if (ContentElement.Name == W.t || ContentElement.Name == W.delText)
-            {
-                sb.AppendFormat(
-                    "Atom {0}: {1} {2} SHA1:{3} ",
-                    PadLocalName(xNamePad, this),
-                    ContentElement.Value,
-                    correlationStatus,
-                    SHA1Hash.Substring(0, 8));
-
-                AppendAncestorsUnidsDump(sb, this);
-            }
-            else
-            {
-                sb.AppendFormat(
-                    "Atom {0}:   {1} SHA1:{2} ",
-                    PadLocalName(xNamePad, this),
-                    correlationStatus,
-                    SHA1Hash.Substring(0, 8));
-
-                AppendAncestorsUnidsDump(sb, this);
-            }
-
-            return sb.ToString();
-        }
-
-        private static string PadLocalName(int xNamePad, ComparisonUnitAtom item)
-        {
-            return (item.ContentElement.Name.LocalName + " ").PadRight(xNamePad, '-') + " ";
-        }
-
-        private static void AppendAncestorsDump(StringBuilder sb, ComparisonUnitAtom sr)
-        {
-            string s = sr
-                .AncestorElements.Select(p => p.Name.LocalName + GetUnid(p) + "/")
-                .StringConcatenate()
-                .TrimEnd('/');
-
-            sb.Append("Ancestors:" + s);
-        }
-
-        private static void AppendAncestorsUnidsDump(StringBuilder sb, ComparisonUnitAtom sr)
-        {
-            var zipped = sr.AncestorElements.Zip(sr.AncestorUnids, (a, u) => new
-            {
-                AncestorElement = a,
-                AncestorUnid = u
-            });
-
-            string s = zipped
-                .Select(p => p.AncestorElement.Name.LocalName + "[" + p.AncestorUnid.Substring(0, 8) + "]/")
-                .StringConcatenate().TrimEnd('/');
-
-            sb.Append("Ancestors:" + s);
-        }
-
-        private static string GetUnid(XElement p)
-        {
-            var unid = (string) p.Attribute(PtOpenXml.Unid);
-            return unid == null ? "" : "[" + unid.Substring(0, 8) + "]";
-        }
-    }
-}

+ 0 - 77
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/ComparisonUnitGroup.cs

@@ -1,77 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text;
-using System.Xml.Linq;
-
-namespace OpenXmlPowerTools
-{
-    internal class ComparisonUnitGroup : ComparisonUnit
-    {
-        public ComparisonUnitGroup(
-            IEnumerable<ComparisonUnit> comparisonUnitList,
-            ComparisonUnitGroupType groupType,
-            int level)
-        {
-            Contents = comparisonUnitList.ToList();
-            ComparisonUnitGroupType = groupType;
-            ComparisonUnit first = Contents.First();
-            ComparisonUnitAtom comparisonUnitAtom = GetFirstComparisonUnitAtomOfGroup(first);
-
-            XElement[] ancestorsToLookAt = comparisonUnitAtom
-                .AncestorElements
-                .Where(e => e.Name == W.tbl || e.Name == W.tr || e.Name == W.tc || e.Name == W.p || e.Name == W.txbxContent)
-                .ToArray();
-
-            XElement ancestor = ancestorsToLookAt[level];
-            if (ancestor == null) throw new OpenXmlPowerToolsException("Internal error: ComparisonUnitGroup");
-
-            SHA1Hash = (string) ancestor.Attribute(PtOpenXml.SHA1Hash);
-            CorrelatedSHA1Hash = (string) ancestor.Attribute(PtOpenXml.CorrelatedSHA1Hash);
-            StructureSHA1Hash = (string) ancestor.Attribute(PtOpenXml.StructureSHA1Hash);
-        }
-
-        public ComparisonUnitGroupType ComparisonUnitGroupType { get; }
-
-        public string CorrelatedSHA1Hash { get; }
-
-        public string StructureSHA1Hash { get; }
-
-        private static ComparisonUnitAtom GetFirstComparisonUnitAtomOfGroup(ComparisonUnit group)
-        {
-            ComparisonUnit thisGroup = group;
-            while (true)
-            {
-                if (thisGroup is ComparisonUnitGroup tg)
-                {
-                    thisGroup = tg.Contents.First();
-                    continue;
-                }
-
-                if (!(thisGroup is ComparisonUnitWord tw))
-                {
-                    throw new OpenXmlPowerToolsException("Internal error: GetFirstComparisonUnitAtomOfGroup");
-                }
-
-                var ca = (ComparisonUnitAtom) tw.Contents.First();
-                return ca;
-            }
-        }
-
-        public override string ToString(int indent)
-        {
-            var sb = new StringBuilder();
-            sb.Append("".PadRight(indent) + "Group Type: " + ComparisonUnitGroupType + " SHA1:" + SHA1Hash + Environment.NewLine);
-
-            foreach (ComparisonUnit comparisonUnitAtom in Contents)
-            {
-                sb.Append(comparisonUnitAtom.ToString(indent + 2));
-            }
-
-            return sb.ToString();
-        }
-    }
-}

+ 0 - 14
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/ComparisonUnitGroupType.cs

@@ -1,14 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-namespace OpenXmlPowerTools
-{
-    internal enum ComparisonUnitGroupType
-    {
-        Paragraph,
-        Table,
-        Row,
-        Cell,
-        Textbox,
-    };
-}

+ 0 - 81
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/ComparisonUnitWord.cs

@@ -1,81 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text;
-using System.Xml.Linq;
-
-namespace OpenXmlPowerTools
-{
-    internal class ComparisonUnitWord : ComparisonUnit
-    {
-        public static readonly XName[] ElementsWithRelationshipIds =
-        {
-            A.blip,
-            A.hlinkClick,
-            A.relIds,
-            C.chart,
-            C.externalData,
-            C.userShapes,
-            DGM.relIds,
-            O.OLEObject,
-            VML.fill,
-            VML.imagedata,
-            VML.stroke,
-            W.altChunk,
-            W.attachedTemplate,
-            W.control,
-            W.dataSource,
-            W.embedBold,
-            W.embedBoldItalic,
-            W.embedItalic,
-            W.embedRegular,
-            W.footerReference,
-            W.headerReference,
-            W.headerSource,
-            W.hyperlink,
-            W.printerSettings,
-            W.recipientData,
-            W.saveThroughXslt,
-            W.sourceFileName,
-            W.src,
-            W.subDoc,
-            WNE.toolbarData
-        };
-
-        public static readonly XName[] RelationshipAttributeNames =
-        {
-            R.embed,
-            R.link,
-            R.id,
-            R.cs,
-            R.dm,
-            R.lo,
-            R.qs,
-            R.href,
-            R.pict
-        };
-
-        public ComparisonUnitWord(IEnumerable<ComparisonUnitAtom> comparisonUnitAtomList)
-        {
-            Contents = comparisonUnitAtomList.OfType<ComparisonUnit>().ToList();
-            string sha1String = Contents.Select(c => c.SHA1Hash).StringConcatenate();
-            SHA1Hash = WmlComparerUtil.SHA1HashStringForUTF8String(sha1String);
-        }
-
-        public override string ToString(int indent)
-        {
-            var sb = new StringBuilder();
-            sb.Append("".PadRight(indent) + "Word SHA1:" + SHA1Hash.Substring(0, 8) + Environment.NewLine);
-
-            foreach (ComparisonUnit comparisonUnitAtom in Contents)
-            {
-                sb.Append(comparisonUnitAtom.ToString(indent + 2) + Environment.NewLine);
-            }
-
-            return sb.ToString();
-        }
-    }
-}

+ 0 - 70
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/CorrelatedSequence.cs

@@ -1,70 +0,0 @@
-// 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.Text;
-
-namespace OpenXmlPowerTools
-{
-    internal class CorrelatedSequence
-    {
-#if DEBUG
-        public string SourceFile;
-        public int SourceLine;
-#endif
-
-        public CorrelatedSequence()
-        {
-#if DEBUG
-            SourceFile = new System.Diagnostics.StackTrace(true).GetFrame(1).GetFileName();
-            SourceLine = new System.Diagnostics.StackTrace(true).GetFrame(1).GetFileLineNumber();
-#endif
-        }
-
-        public CorrelationStatus CorrelationStatus { get; set; }
-
-        // if ComparisonUnitList1 == null and ComparisonUnitList2 contains sequence, then inserted content.
-        // if ComparisonUnitList2 == null and ComparisonUnitList1 contains sequence, then deleted content.
-        // if ComparisonUnitList2 contains sequence and ComparisonUnitList1 contains sequence, then either is Unknown or Equal.
-        public ComparisonUnit[] ComparisonUnitArray1 { get; set; }
-
-        public ComparisonUnit[] ComparisonUnitArray2 { get; set; }
-
-        public override string ToString()
-        {
-            var sb = new StringBuilder();
-            const string indentString = "  ";
-            const string indentString4 = "    ";
-            sb.Append("CorrelatedSequence =====" + Environment.NewLine);
-#if DEBUG
-            sb.Append(indentString + "Created at Line: " + SourceLine + Environment.NewLine);
-#endif
-            sb.Append(indentString + "CorrelatedItem =====" + Environment.NewLine);
-            sb.Append(indentString4 + "CorrelationStatus: " + CorrelationStatus + Environment.NewLine);
-            if (CorrelationStatus == CorrelationStatus.Equal)
-            {
-                sb.Append(indentString4 + "ComparisonUnitList =====" + Environment.NewLine);
-                foreach (ComparisonUnit item in ComparisonUnitArray2)
-                    sb.Append(item.ToString(6) + Environment.NewLine);
-            }
-            else
-            {
-                if (ComparisonUnitArray1 != null)
-                {
-                    sb.Append(indentString4 + "ComparisonUnitList1 =====" + Environment.NewLine);
-                    foreach (ComparisonUnit item in ComparisonUnitArray1)
-                        sb.Append(item.ToString(6) + Environment.NewLine);
-                }
-
-                if (ComparisonUnitArray2 != null)
-                {
-                    sb.Append(indentString4 + "ComparisonUnitList2 =====" + Environment.NewLine);
-                    foreach (ComparisonUnit item in ComparisonUnitArray2)
-                        sb.Append(item.ToString(6) + Environment.NewLine);
-                }
-            }
-
-            return sb.ToString();
-        }
-    }
-}

+ 0 - 16
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/CorrelationStatus.cs

@@ -1,16 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-namespace OpenXmlPowerTools
-{
-    public enum CorrelationStatus
-    {
-        Nil,
-        Normal,
-        Unknown,
-        Inserted,
-        Deleted,
-        Equal,
-        Group,
-    }
-}

+ 0 - 15
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/PartSHA1HashAnnotation.cs

@@ -1,15 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-namespace OpenXmlPowerTools
-{
-    internal class PartSHA1HashAnnotation
-    {
-        public string Hash;
-
-        public PartSHA1HashAnnotation(string hash)
-        {
-            Hash = hash;
-        }
-    }
-}

+ 0 - 12
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WithHierarchicalGroupingKey.cs

@@ -1,12 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-namespace OpenXmlPowerTools
-{
-    internal class WithHierarchicalGroupingKey
-    {
-        public string[] HierarchicalGroupingArray { get; set; }
-
-        public ComparisonUnitWord ComparisonUnitWord { get; set; }
-    }
-}

+ 0 - 401
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Internal.Methods.ComparisonUnits.cs

@@ -1,401 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public static partial class WmlComparer
-    {
-        #region CreateComparisonUnitAtomList
-
-        internal static ComparisonUnitAtom[] CreateComparisonUnitAtomList(
-            OpenXmlPart part,
-            XElement contentParent,
-            WmlComparerSettings settings)
-        {
-            VerifyNoInvalidContent(contentParent);
-            AssignUnidToAllElements(contentParent); // add the Guid id to every element
-            MoveLastSectPrIntoLastParagraph(contentParent);
-            ComparisonUnitAtom[] cal = CreateComparisonUnitAtomListInternal(part, contentParent, settings).ToArray();
-
-            if (False)
-            {
-                var sb = new StringBuilder();
-                foreach (ComparisonUnitAtom item in cal)
-                    sb.Append(item + Environment.NewLine);
-                string sbs = sb.ToString();
-                TestUtil.NotePad(sbs);
-            }
-
-            return cal;
-        }
-
-        private static void VerifyNoInvalidContent(XElement contentParent)
-        {
-            XElement invalidElement = contentParent.Descendants().FirstOrDefault(d => InvalidElements.Contains(d.Name));
-            if (invalidElement == null)
-                return;
-
-            throw new NotSupportedException("Document contains " + invalidElement.Name.LocalName);
-        }
-
-        private static void MoveLastSectPrIntoLastParagraph(XElement contentParent)
-        {
-            List<XElement> lastSectPrList = contentParent.Elements(W.sectPr).ToList();
-            if (lastSectPrList.Count() > 1)
-                throw new OpenXmlPowerToolsException("Invalid document");
-
-            XElement lastSectPr = lastSectPrList.FirstOrDefault();
-            if (lastSectPr != null)
-            {
-                XElement lastParagraph = contentParent.Elements(W.p).LastOrDefault();
-                if (lastParagraph == null)
-                    throw new OpenXmlPowerToolsException("Invalid document");
-
-                XElement pPr = lastParagraph.Element(W.pPr);
-                if (pPr == null)
-                {
-                    pPr = new XElement(W.pPr);
-                    lastParagraph.AddFirst(W.pPr);
-                }
-
-                pPr.Add(lastSectPr);
-                contentParent.Elements(W.sectPr).Remove();
-            }
-        }
-
-        private static List<ComparisonUnitAtom> CreateComparisonUnitAtomListInternal(
-            OpenXmlPart part,
-            XElement contentParent,
-            WmlComparerSettings settings)
-        {
-            var comparisonUnitAtomList = new List<ComparisonUnitAtom>();
-            CreateComparisonUnitAtomListRecurse(part, contentParent, comparisonUnitAtomList, settings);
-            return comparisonUnitAtomList;
-        }
-
-        private static void CreateComparisonUnitAtomListRecurse(
-            OpenXmlPart part,
-            XElement element,
-            List<ComparisonUnitAtom> comparisonUnitAtomList,
-            WmlComparerSettings settings)
-        {
-            if (element.Name == W.body || element.Name == W.footnote || element.Name == W.endnote)
-            {
-                foreach (XElement item in element.Elements())
-                    CreateComparisonUnitAtomListRecurse(part, item, comparisonUnitAtomList, settings);
-                return;
-            }
-
-            if (element.Name == W.p)
-            {
-                IEnumerable<XElement> paraChildrenToProcess = element
-                    .Elements()
-                    .Where(e => e.Name != W.pPr);
-                foreach (XElement item in paraChildrenToProcess)
-                    CreateComparisonUnitAtomListRecurse(part, item, comparisonUnitAtomList, settings);
-                XElement paraProps = element.Element(W.pPr);
-                if (paraProps == null)
-                {
-                    var pPrComparisonUnitAtom = new ComparisonUnitAtom(
-                        new XElement(W.pPr),
-                        element.AncestorsAndSelf()
-                            .TakeWhile(a => a.Name != W.body && a.Name != W.footnotes && a.Name != W.endnotes).Reverse()
-                            .ToArray(),
-                        part,
-                        settings);
-                    comparisonUnitAtomList.Add(pPrComparisonUnitAtom);
-                }
-                else
-                {
-                    var pPrComparisonUnitAtom = new ComparisonUnitAtom(
-                        paraProps,
-                        element.AncestorsAndSelf()
-                            .TakeWhile(a => a.Name != W.body && a.Name != W.footnotes && a.Name != W.endnotes).Reverse()
-                            .ToArray(),
-                        part,
-                        settings);
-                    comparisonUnitAtomList.Add(pPrComparisonUnitAtom);
-                }
-
-                return;
-            }
-
-            if (element.Name == W.r)
-            {
-                IEnumerable<XElement> runChildrenToProcess = element
-                    .Elements()
-                    .Where(e => e.Name != W.rPr);
-                foreach (XElement item in runChildrenToProcess)
-                    CreateComparisonUnitAtomListRecurse(part, item, comparisonUnitAtomList, settings);
-                return;
-            }
-
-            if (element.Name == W.t || element.Name == W.delText)
-            {
-                string val = element.Value;
-                foreach (char ch in val)
-                {
-                    var sr = new ComparisonUnitAtom(
-                        new XElement(element.Name, ch),
-                        element.AncestorsAndSelf()
-                            .TakeWhile(a => a.Name != W.body && a.Name != W.footnotes && a.Name != W.endnotes).Reverse()
-                            .ToArray(),
-                        part,
-                        settings);
-                    comparisonUnitAtomList.Add(sr);
-                }
-
-                return;
-            }
-
-            if (AllowableRunChildren.Contains(element.Name) || element.Name == W._object)
-            {
-                var sr3 = new ComparisonUnitAtom(
-                    element,
-                    element.AncestorsAndSelf().TakeWhile(a => a.Name != W.body && a.Name != W.footnotes && a.Name != W.endnotes)
-                        .Reverse().ToArray(),
-                    part,
-                    settings);
-                comparisonUnitAtomList.Add(sr3);
-                return;
-            }
-
-            RecursionInfo re = RecursionElements.FirstOrDefault(z => z.ElementName == element.Name);
-            if (re != null)
-            {
-                AnnotateElementWithProps(part, element, comparisonUnitAtomList, re.ChildElementPropertyNames, settings);
-                return;
-            }
-
-            if (ElementsToThrowAway.Contains(element.Name))
-                return;
-
-            AnnotateElementWithProps(part, element, comparisonUnitAtomList, null, settings);
-        }
-
-        private static void AnnotateElementWithProps(
-            OpenXmlPart part,
-            XElement element,
-            List<ComparisonUnitAtom> comparisonUnitAtomList,
-            XName[] childElementPropertyNames,
-            WmlComparerSettings settings)
-        {
-            IEnumerable<XElement> runChildrenToProcess;
-            if (childElementPropertyNames == null)
-                runChildrenToProcess = element.Elements();
-            else
-                runChildrenToProcess = element
-                    .Elements()
-                    .Where(e => !childElementPropertyNames.Contains(e.Name));
-
-            foreach (XElement item in runChildrenToProcess)
-                CreateComparisonUnitAtomListRecurse(part, item, comparisonUnitAtomList, settings);
-        }
-
-        #endregion CreateComparisonUnitAtomList
-
-        #region GetComparisonUnitList
-
-        // The following method must be made internal if we ever turn this part of the partial class
-        // into its own class.
-        private static ComparisonUnit[] GetComparisonUnitList(
-            ComparisonUnitAtom[] comparisonUnitAtomList,
-            WmlComparerSettings settings)
-        {
-            var seed = new Atgbw
-            {
-                Key = null,
-                ComparisonUnitAtomMember = null,
-                NextIndex = 0
-            };
-
-            IEnumerable<Atgbw> groupingKey = comparisonUnitAtomList
-                .Rollup(seed, (sr, prevAtgbw, i) =>
-                {
-                    int? key;
-                    int nextIndex = prevAtgbw.NextIndex;
-                    if (sr.ContentElement.Name == W.t)
-                    {
-                        string chr = sr.ContentElement.Value;
-                        char ch = chr[0];
-                        if (ch == '.' || ch == ',')
-                        {
-                            var beforeIsDigit = false;
-                            if (i > 0)
-                            {
-                                ComparisonUnitAtom prev = comparisonUnitAtomList[i - 1];
-                                if (prev.ContentElement.Name == W.t && char.IsDigit(prev.ContentElement.Value[0]))
-                                    beforeIsDigit = true;
-                            }
-
-                            var afterIsDigit = false;
-                            if (i < comparisonUnitAtomList.Length - 1)
-                            {
-                                ComparisonUnitAtom next = comparisonUnitAtomList[i + 1];
-                                if (next.ContentElement.Name == W.t && char.IsDigit(next.ContentElement.Value[0]))
-                                    afterIsDigit = true;
-                            }
-
-                            if (beforeIsDigit || afterIsDigit)
-                            {
-                                key = nextIndex;
-                            }
-                            else
-                            {
-                                nextIndex++;
-                                key = nextIndex;
-                                nextIndex++;
-                            }
-                        }
-                        else if (settings.WordSeparators.Contains(ch))
-                        {
-                            nextIndex++;
-                            key = nextIndex;
-                            nextIndex++;
-                        }
-                        else
-                        {
-                            key = nextIndex;
-                        }
-                    }
-                    else if (WordBreakElements.Contains(sr.ContentElement.Name))
-                    {
-                        nextIndex++;
-                        key = nextIndex;
-                        nextIndex++;
-                    }
-                    else
-                    {
-                        key = nextIndex;
-                    }
-
-                    return new Atgbw
-                    {
-                        Key = key,
-                        ComparisonUnitAtomMember = sr,
-                        NextIndex = nextIndex
-                    };
-                })
-                .ToArray();
-
-            if (False)
-            {
-                var sb = new StringBuilder();
-                foreach (Atgbw item in groupingKey)
-                {
-                    sb.Append(item.Key + Environment.NewLine);
-                    sb.Append("    " + item.ComparisonUnitAtomMember.ToString(0) + Environment.NewLine);
-                }
-
-                string sbs = sb.ToString();
-                TestUtil.NotePad(sbs);
-            }
-
-            IEnumerable<IGrouping<int?, Atgbw>> groupedByWords = groupingKey
-                .GroupAdjacent(gc => gc.Key)
-                .ToArray();
-
-            if (False)
-            {
-                var sb = new StringBuilder();
-                foreach (IGrouping<int?, Atgbw> group in groupedByWords)
-                {
-                    sb.Append("Group ===== " + @group.Key + Environment.NewLine);
-                    foreach (Atgbw gc in @group)
-                    {
-                        sb.Append("    " + gc.ComparisonUnitAtomMember.ToString(0) + Environment.NewLine);
-                    }
-                }
-
-                string sbs = sb.ToString();
-                TestUtil.NotePad(sbs);
-            }
-
-            WithHierarchicalGroupingKey[] withHierarchicalGroupingKey = groupedByWords
-                .Select(g =>
-                    {
-                        string[] hierarchicalGroupingArray = g
-                            .First()
-                            .ComparisonUnitAtomMember
-                            .AncestorElements
-                            .Where(a => ComparisonGroupingElements.Contains(a.Name))
-                            .Select(a => a.Name.LocalName + ":" + (string) a.Attribute(PtOpenXml.Unid))
-                            .ToArray();
-
-                        return new WithHierarchicalGroupingKey
-                        {
-                            ComparisonUnitWord = new ComparisonUnitWord(g.Select(gc => gc.ComparisonUnitAtomMember)),
-                            HierarchicalGroupingArray = hierarchicalGroupingArray
-                        };
-                    }
-                )
-                .ToArray();
-
-            if (False)
-            {
-                var sb = new StringBuilder();
-                foreach (WithHierarchicalGroupingKey group in withHierarchicalGroupingKey)
-                {
-                    sb.Append("Grouping Array: " +
-                              @group.HierarchicalGroupingArray.Select(gam => gam + " - ").StringConcatenate() +
-                              Environment.NewLine);
-                    foreach (ComparisonUnit gc in @group.ComparisonUnitWord.Contents)
-                    {
-                        sb.Append("    " + gc.ToString(0) + Environment.NewLine);
-                    }
-                }
-
-                string sbs = sb.ToString();
-                TestUtil.NotePad(sbs);
-            }
-
-            ComparisonUnit[] cul = GetHierarchicalComparisonUnits(withHierarchicalGroupingKey, 0).ToArray();
-
-            if (False)
-            {
-                string str = ComparisonUnit.ComparisonUnitListToString(cul);
-                TestUtil.NotePad(str);
-            }
-
-            return cul;
-        }
-
-        private static IEnumerable<ComparisonUnit> GetHierarchicalComparisonUnits(
-            IEnumerable<WithHierarchicalGroupingKey> input,
-            int level)
-        {
-            IEnumerable<IGrouping<string, WithHierarchicalGroupingKey>> grouped = input
-                .GroupAdjacent(
-                    whgk => level >= whgk.HierarchicalGroupingArray.Length ? "" : whgk.HierarchicalGroupingArray[level]);
-
-            List<ComparisonUnit> retList = grouped
-                .Select(gc =>
-                {
-                    if (gc.Key == "")
-                    {
-                        return (IEnumerable<ComparisonUnit>) gc.Select(whgk => whgk.ComparisonUnitWord).ToList();
-                    }
-
-                    string[] spl = gc.Key.Split(':');
-                    ComparisonUnitGroupType groupType = WmlComparerUtil.ComparisonUnitGroupTypeFromLocalName(spl[0]);
-                    IEnumerable<ComparisonUnit> childHierarchicalComparisonUnits = GetHierarchicalComparisonUnits(gc, level + 1);
-                    var newCompUnitGroup = new ComparisonUnitGroup(childHierarchicalComparisonUnits, groupType, level);
-
-                    return new[] { newCompUnitGroup };
-                })
-                .SelectMany(m => m)
-                .ToList();
-
-            return retList;
-        }
-
-        #endregion GetComparisonUnitList
-    }
-}

+ 0 - 276
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.Fields.cs

@@ -1,276 +0,0 @@
-// 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.Xml.Linq;
-
-namespace OpenXmlPowerTools
-{
-    public static partial class WmlComparer
-    {
-#pragma warning disable 414
-        private static readonly bool False = false;
-        private static readonly bool True = true;
-        private static readonly bool SaveIntermediateFilesForDebugging = false;
-#pragma warning restore 414
-
-        private static readonly string NewLine = Environment.NewLine;
-
-        private static readonly XAttribute[] NamespaceAttributes =
-        {
-            new XAttribute(XNamespace.Xmlns + "wpc", WPC.wpc),
-            new XAttribute(XNamespace.Xmlns + "mc", MC.mc),
-            new XAttribute(XNamespace.Xmlns + "o", O.o),
-            new XAttribute(XNamespace.Xmlns + "r", R.r),
-            new XAttribute(XNamespace.Xmlns + "m", M.m),
-            new XAttribute(XNamespace.Xmlns + "v", VML.vml),
-            new XAttribute(XNamespace.Xmlns + "wp14", WP14.wp14),
-            new XAttribute(XNamespace.Xmlns + "wp", WP.wp),
-            new XAttribute(XNamespace.Xmlns + "w10", W10.w10),
-            new XAttribute(XNamespace.Xmlns + "w", W.w),
-            new XAttribute(XNamespace.Xmlns + "w14", W14.w14),
-            new XAttribute(XNamespace.Xmlns + "wpg", WPG.wpg),
-            new XAttribute(XNamespace.Xmlns + "wpi", WPI.wpi),
-            new XAttribute(XNamespace.Xmlns + "wne", WNE.wne),
-            new XAttribute(XNamespace.Xmlns + "wps", WPS.wps),
-            new XAttribute(MC.Ignorable, "w14 wp14")
-        };
-
-        private static readonly XName[] RevElementsWithNoText =
-        {
-            M.oMath,
-            M.oMathPara,
-            W.drawing
-        };
-
-        private static readonly XName[] AttributesToTrimWhenCloning =
-        {
-            WP14.anchorId,
-            WP14.editId,
-            "ObjectID",
-            "ShapeID",
-            "id",
-            "type"
-        };
-
-        private static int _maxId;
-
-        private static readonly XName[] WordBreakElements =
-        {
-            W.pPr,
-            W.tab,
-            W.br,
-            W.continuationSeparator,
-            W.cr,
-            W.dayLong,
-            W.dayShort,
-            W.drawing,
-            W.pict,
-            W.endnoteRef,
-            W.footnoteRef,
-            W.monthLong,
-            W.monthShort,
-            W.noBreakHyphen,
-            W._object,
-            W.ptab,
-            W.separator,
-            W.sym,
-            W.yearLong,
-            W.yearShort,
-            M.oMathPara,
-            M.oMath,
-            W.footnoteReference,
-            W.endnoteReference
-        };
-
-        private static readonly XName[] AllowableRunChildren =
-        {
-            W.br,
-            W.drawing,
-            W.cr,
-            W.dayLong,
-            W.dayShort,
-            W.footnoteReference,
-            W.endnoteReference,
-            W.monthLong,
-            W.monthShort,
-            W.noBreakHyphen,
-
-            //W._object,
-            W.pgNum,
-            W.ptab,
-            W.softHyphen,
-            W.sym,
-            W.tab,
-            W.yearLong,
-            W.yearShort,
-            M.oMathPara,
-            M.oMath,
-            W.fldChar,
-            W.instrText
-        };
-
-        private static readonly XName[] ElementsToThrowAway =
-        {
-            W.bookmarkStart,
-            W.bookmarkEnd,
-            W.commentRangeStart,
-            W.commentRangeEnd,
-            W.lastRenderedPageBreak,
-            W.proofErr,
-            W.tblPr,
-            W.sectPr,
-            W.permEnd,
-            W.permStart,
-            W.footnoteRef,
-            W.endnoteRef,
-            W.separator,
-            W.continuationSeparator
-        };
-
-        private static readonly XName[] ElementsToHaveSha1Hash =
-        {
-            W.p,
-            W.tbl,
-            W.tr,
-            W.tc,
-            W.drawing,
-            W.pict,
-            W.txbxContent
-        };
-
-        private static readonly XName[] InvalidElements =
-        {
-            W.altChunk,
-            W.customXml,
-            W.customXmlDelRangeEnd,
-            W.customXmlDelRangeStart,
-            W.customXmlInsRangeEnd,
-            W.customXmlInsRangeStart,
-            W.customXmlMoveFromRangeEnd,
-            W.customXmlMoveFromRangeStart,
-            W.customXmlMoveToRangeEnd,
-            W.customXmlMoveToRangeStart,
-            W.moveFrom,
-            W.moveFromRangeStart,
-            W.moveFromRangeEnd,
-            W.moveTo,
-            W.moveToRangeStart,
-            W.moveToRangeEnd,
-            W.subDoc
-        };
-
-        private static readonly RecursionInfo[] RecursionElements =
-        {
-            new RecursionInfo
-            {
-                ElementName = W.del,
-                ChildElementPropertyNames = null
-            },
-            new RecursionInfo
-            {
-                ElementName = W.ins,
-                ChildElementPropertyNames = null
-            },
-            new RecursionInfo
-            {
-                ElementName = W.tbl,
-                ChildElementPropertyNames = new[] { W.tblPr, W.tblGrid, W.tblPrEx }
-            },
-            new RecursionInfo
-            {
-                ElementName = W.tr,
-                ChildElementPropertyNames = new[] { W.trPr, W.tblPrEx }
-            },
-            new RecursionInfo
-            {
-                ElementName = W.tc,
-                ChildElementPropertyNames = new[] { W.tcPr, W.tblPrEx }
-            },
-            new RecursionInfo
-            {
-                ElementName = W.pict,
-                ChildElementPropertyNames = new[] { VML.shapetype }
-            },
-            new RecursionInfo
-            {
-                ElementName = VML.group,
-                ChildElementPropertyNames = null
-            },
-            new RecursionInfo
-            {
-                ElementName = VML.shape,
-                ChildElementPropertyNames = null
-            },
-            new RecursionInfo
-            {
-                ElementName = VML.rect,
-                ChildElementPropertyNames = null
-            },
-            new RecursionInfo
-            {
-                ElementName = VML.textbox,
-                ChildElementPropertyNames = null
-            },
-            new RecursionInfo
-            {
-                ElementName = O._lock,
-                ChildElementPropertyNames = null
-            },
-            new RecursionInfo
-            {
-                ElementName = W.txbxContent,
-                ChildElementPropertyNames = null
-            },
-            new RecursionInfo
-            {
-                ElementName = W10.wrap,
-                ChildElementPropertyNames = null
-            },
-            new RecursionInfo
-            {
-                ElementName = W.sdt,
-                ChildElementPropertyNames = new[] { W.sdtPr, W.sdtEndPr }
-            },
-            new RecursionInfo
-            {
-                ElementName = W.sdtContent,
-                ChildElementPropertyNames = null
-            },
-            new RecursionInfo
-            {
-                ElementName = W.hyperlink,
-                ChildElementPropertyNames = null
-            },
-            new RecursionInfo
-            {
-                ElementName = W.fldSimple,
-                ChildElementPropertyNames = null
-            },
-            new RecursionInfo
-            {
-                ElementName = VML.shapetype,
-                ChildElementPropertyNames = null
-            },
-            new RecursionInfo
-            {
-                ElementName = W.smartTag,
-                ChildElementPropertyNames = new[] { W.smartTagPr }
-            },
-            new RecursionInfo
-            {
-                ElementName = W.ruby,
-                ChildElementPropertyNames = new[] { W.rubyPr }
-            }
-        };
-
-        private static readonly XName[] ComparisonGroupingElements =
-        {
-            W.p,
-            W.tbl,
-            W.tr,
-            W.tc,
-            W.txbxContent
-        };
-    }
-}

+ 0 - 328
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.Methods.Hashing.cs

@@ -1,328 +0,0 @@
-// 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.Generic;
-using System.IO;
-using System.Linq;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public static partial class WmlComparer
-    {
-        private static WmlDocument HashBlockLevelContent(
-            WmlDocument source,
-            WmlDocument sourceAfterProc,
-            WmlComparerSettings settings)
-        {
-            using (var msSource = new MemoryStream())
-            using (var msAfterProc = new MemoryStream())
-            {
-                msSource.Write(source.DocumentByteArray, 0, source.DocumentByteArray.Length);
-                msAfterProc.Write(sourceAfterProc.DocumentByteArray, 0, sourceAfterProc.DocumentByteArray.Length);
-
-                using (WordprocessingDocument wDocSource = WordprocessingDocument.Open(msSource, true))
-                using (WordprocessingDocument wDocAfterProc = WordprocessingDocument.Open(msAfterProc, true))
-                {
-                    // create Unid dictionary for source
-                    XDocument sourceMainXDoc = wDocSource.MainDocumentPart.GetXDocument();
-                    XElement sourceMainRoot = sourceMainXDoc.Root ?? throw new ArgumentException();
-                    Dictionary<string, XElement> sourceUnidDict = sourceMainRoot
-                        .Descendants()
-                        .Where(d => d.Name == W.p || d.Name == W.tbl || d.Name == W.tr)
-                        .ToDictionary(d => (string) d.Attribute(PtOpenXml.Unid));
-
-                    XDocument afterProcMainXDoc = wDocAfterProc.MainDocumentPart.GetXDocument();
-                    XElement afterProcMainRoot = afterProcMainXDoc.Root ?? throw new ArgumentException();
-                    IEnumerable<XElement> blockLevelElements = afterProcMainRoot
-                        .Descendants()
-                        .Where(d => d.Name == W.p || d.Name == W.tbl || d.Name == W.tr);
-
-                    foreach (XElement blockLevelContent in blockLevelElements)
-                    {
-                        var cloneBlockLevelContentForHashing = (XElement) CloneBlockLevelContentForHashing(
-                            wDocAfterProc.MainDocumentPart,
-                            blockLevelContent,
-                            true,
-                            settings);
-
-                        string shaString = cloneBlockLevelContentForHashing
-                            .ToString(SaveOptions.DisableFormatting)
-                            .Replace(" xmlns=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"", "");
-
-                        string sha1Hash = WmlComparerUtil.SHA1HashStringForUTF8String(shaString);
-                        var thisUnid = (string) blockLevelContent.Attribute(PtOpenXml.Unid);
-                        if (thisUnid != null)
-                        {
-                            if (sourceUnidDict.ContainsKey(thisUnid))
-                            {
-                                XElement correlatedBlockLevelContent = sourceUnidDict[thisUnid];
-                                correlatedBlockLevelContent.Add(new XAttribute(PtOpenXml.CorrelatedSHA1Hash, sha1Hash));
-                            }
-                        }
-                    }
-
-                    wDocSource.MainDocumentPart.PutXDocument();
-                }
-
-                var sourceWithCorrelatedSHA1Hash = new WmlDocument(source.FileName, msSource.ToArray());
-                return sourceWithCorrelatedSHA1Hash;
-            }
-        }
-
-        // prohibit
-        // - altChunk
-        // - subDoc
-        // - contentPart
-
-        // This strips all text nodes from the XML tree, thereby leaving only the structure.
-
-        private static object CloneBlockLevelContentForHashing(
-            OpenXmlPart mainDocumentPart,
-            XNode node,
-            bool includeRelatedParts,
-            WmlComparerSettings settings)
-        {
-            if (node is XElement element)
-            {
-                if (element.Name == W.bookmarkStart ||
-                    element.Name == W.bookmarkEnd ||
-                    element.Name == W.pPr ||
-                    element.Name == W.rPr)
-                {
-                    return null;
-                }
-
-                if (element.Name == W.p)
-                {
-                    var clonedPara = new XElement(element.Name,
-                        element.Attributes().Where(a => a.Name != W.rsid &&
-                                                        a.Name != W.rsidDel &&
-                                                        a.Name != W.rsidP &&
-                                                        a.Name != W.rsidR &&
-                                                        a.Name != W.rsidRDefault &&
-                                                        a.Name != W.rsidRPr &&
-                                                        a.Name != W.rsidSect &&
-                                                        a.Name != W.rsidTr &&
-                                                        a.Name.Namespace != PtOpenXml.pt),
-                        element.Nodes().Select(n =>
-                            CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
-
-                    IEnumerable<IGrouping<bool, XElement>> groupedRuns = clonedPara
-                        .Elements()
-                        .GroupAdjacent(e => e.Name == W.r &&
-                                            e.Elements().Count() == 1 &&
-                                            e.Element(W.t) != null);
-
-                    var clonedParaWithGroupedRuns = new XElement(element.Name,
-                        groupedRuns.Select(g =>
-                        {
-                            if (g.Key)
-                            {
-                                string text = g.Select(t => t.Value).StringConcatenate();
-                                if (settings.CaseInsensitive)
-                                    text = text.ToUpper(settings.CultureInfo);
-                                var newRun = (object) new XElement(W.r,
-                                    new XElement(W.t,
-                                        text));
-                                return newRun;
-                            }
-
-                            return g;
-                        }));
-
-                    return clonedParaWithGroupedRuns;
-                }
-
-                if (element.Name == W.r)
-                {
-                    IEnumerable<XElement> clonedRuns = element
-                        .Elements()
-                        .Where(e => e.Name != W.rPr)
-                        .Select(rc => new XElement(W.r,
-                            CloneBlockLevelContentForHashing(mainDocumentPart, rc, includeRelatedParts, settings)));
-                    return clonedRuns;
-                }
-
-                if (element.Name == W.tbl)
-                {
-                    var clonedTable = new XElement(W.tbl,
-                        element.Elements(W.tr).Select(n =>
-                            CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
-                    return clonedTable;
-                }
-
-                if (element.Name == W.tr)
-                {
-                    var clonedRow = new XElement(W.tr,
-                        element.Elements(W.tc).Select(n =>
-                            CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
-                    return clonedRow;
-                }
-
-                if (element.Name == W.tc)
-                {
-                    var clonedCell = new XElement(W.tc,
-                        element.Elements().Select(n =>
-                            CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
-                    return clonedCell;
-                }
-
-                if (element.Name == W.tcPr)
-                {
-                    var clonedCellProps = new XElement(W.tcPr,
-                        element.Elements(W.gridSpan).Select(n =>
-                            CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
-                    return clonedCellProps;
-                }
-
-                if (element.Name == W.gridSpan)
-                {
-                    var clonedGridSpan = new XElement(W.gridSpan,
-                        new XAttribute("val", (string) element.Attribute(W.val)));
-                    return clonedGridSpan;
-                }
-
-                if (element.Name == W.txbxContent)
-                {
-                    var clonedTextbox = new XElement(W.txbxContent,
-                        element.Elements().Select(n =>
-                            CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
-                    return clonedTextbox;
-                }
-
-                if (includeRelatedParts)
-                {
-                    if (ComparisonUnitWord.ElementsWithRelationshipIds.Contains(element.Name))
-                    {
-                        var newElement = new XElement(element.Name,
-                            element.Attributes()
-                                .Where(a => a.Name.Namespace != PtOpenXml.pt)
-                                .Where(a => !AttributesToTrimWhenCloning.Contains(a.Name))
-                                .Select(a =>
-                                {
-                                    if (!ComparisonUnitWord.RelationshipAttributeNames.Contains(a.Name))
-                                        return a;
-
-                                    var rId = (string) a;
-
-                                    // could be an hyperlink relationship
-                                    try
-                                    {
-                                        OpenXmlPart oxp = mainDocumentPart.GetPartById(rId);
-                                        if (oxp == null)
-                                            throw new FileFormatException("Invalid WordprocessingML Document");
-
-                                        var anno = oxp.Annotation<PartSHA1HashAnnotation>();
-                                        if (anno != null)
-                                            return new XAttribute(a.Name, anno.Hash);
-
-                                        if (!oxp.ContentType.EndsWith("xml"))
-                                        {
-                                            using (Stream str = oxp.GetStream())
-                                            {
-                                                byte[] ba;
-                                                using (var br = new BinaryReader(str))
-                                                {
-                                                    ba = br.ReadBytes((int) str.Length);
-                                                }
-
-                                                string sha1 = WmlComparerUtil.SHA1HashStringForByteArray(ba);
-                                                oxp.AddAnnotation(new PartSHA1HashAnnotation(sha1));
-                                                return new XAttribute(a.Name, sha1);
-                                            }
-                                        }
-                                    }
-                                    catch (ArgumentOutOfRangeException)
-                                    {
-                                        HyperlinkRelationship hr =
-                                            mainDocumentPart.HyperlinkRelationships.FirstOrDefault(z => z.Id == rId);
-                                        if (hr != null)
-                                        {
-                                            string str = hr.Uri.ToString();
-                                            return new XAttribute(a.Name, str);
-                                        }
-
-                                        // could be an external relationship
-                                        ExternalRelationship er =
-                                            mainDocumentPart.ExternalRelationships.FirstOrDefault(z => z.Id == rId);
-                                        if (er != null)
-                                        {
-                                            string str = er.Uri.ToString();
-                                            return new XAttribute(a.Name, str);
-                                        }
-
-                                        return new XAttribute(a.Name, "NULL Relationship");
-                                    }
-
-                                    return null;
-                                }),
-                            element.Nodes().Select(n =>
-                                CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
-                        return newElement;
-                    }
-                }
-
-                if (element.Name == VML.shape)
-                {
-                    return new XElement(element.Name,
-                        element.Attributes()
-                            .Where(a => a.Name.Namespace != PtOpenXml.pt)
-                            .Where(a => a.Name != "style" && a.Name != "id" && a.Name != "type"),
-                        element.Nodes().Select(n =>
-                            CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
-                }
-
-                if (element.Name == O.OLEObject)
-                {
-                    var o = new XElement(element.Name,
-                        element.Attributes()
-                            .Where(a => a.Name.Namespace != PtOpenXml.pt)
-                            .Where(a => a.Name != "ObjectID" && a.Name != R.id),
-                        element.Nodes().Select(n =>
-                            CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
-                    return o;
-                }
-
-                if (element.Name == W._object)
-                {
-                    var o = new XElement(element.Name,
-                        element.Attributes()
-                            .Where(a => a.Name.Namespace != PtOpenXml.pt),
-                        element.Nodes().Select(n =>
-                            CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
-                    return o;
-                }
-
-                if (element.Name == WP.docPr)
-                {
-                    return new XElement(element.Name,
-                        element.Attributes()
-                            .Where(a => a.Name.Namespace != PtOpenXml.pt && a.Name != "id"),
-                        element.Nodes().Select(n =>
-                            CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
-                }
-
-                return new XElement(element.Name,
-                    element.Attributes()
-                        .Where(a => a.Name.Namespace != PtOpenXml.pt)
-                        .Where(a => !AttributesToTrimWhenCloning.Contains(a.Name)),
-                    element.Nodes().Select(n =>
-                        CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
-            }
-
-            if (settings.CaseInsensitive)
-            {
-                if (node is XText xt)
-                {
-                    string newText = xt.Value.ToUpper(settings.CultureInfo);
-                    return new XText(newText);
-                }
-            }
-
-            return node;
-        }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 1326
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.Methods.Lcs.cs


+ 0 - 331
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.Methods.PreProcessMarkup.cs

@@ -1,331 +0,0 @@
-// 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.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.IO;
-using System.Linq;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public static partial class WmlComparer
-    {
-        private static WmlDocument PreProcessMarkup(WmlDocument source, int startingIdForFootnotesEndnotes)
-        {
-            // open and close to get rid of MC content
-            using (var ms = new MemoryStream())
-            {
-                ms.Write(source.DocumentByteArray, 0, source.DocumentByteArray.Length);
-                var os = new OpenSettings
-                {
-                    MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(
-                        MarkupCompatibilityProcessMode.ProcessAllParts,
-                        FileFormatVersions.Office2007)
-                };
-
-                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true, os))
-                {
-                    OpenXmlPartRootElement unused = wDoc.MainDocumentPart.RootElement;
-                    if (wDoc.MainDocumentPart.FootnotesPart != null)
-                    {
-                        // contrary to what you might think, looking at the API, it is necessary to access the root element of each part to cause
-                        // the SDK to process MC markup.
-                        OpenXmlPartRootElement unused1 = wDoc.MainDocumentPart.FootnotesPart.RootElement;
-                    }
-
-                    if (wDoc.MainDocumentPart.EndnotesPart != null)
-                    {
-                        OpenXmlPartRootElement unused1 = wDoc.MainDocumentPart.EndnotesPart.RootElement;
-                    }
-                }
-
-                source = new WmlDocument(source.FileName, ms.ToArray());
-            }
-
-            // open and close to get rid of MC content
-            using (var ms = new MemoryStream())
-            {
-                ms.Write(source.DocumentByteArray, 0, source.DocumentByteArray.Length);
-                var os = new OpenSettings
-                {
-                    MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(
-                        MarkupCompatibilityProcessMode.ProcessAllParts,
-                        FileFormatVersions.Office2007)
-                };
-
-                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true, os))
-                {
-                    TestForInvalidContent(wDoc);
-                    RemoveExistingPowerToolsMarkup(wDoc);
-
-                    // Removing content controls, field codes, and bookmarks is a no-no for many use cases.
-                    // We need content controls, e.g., on the title page. Field codes are required for
-                    // automatic cross-references, which require bookmarks.
-                    // TODO: Revisit
-                    var msSettings = new SimplifyMarkupSettings
-                    {
-                        RemoveBookmarks = true,
-
-                        AcceptRevisions = false,
-                        RemoveComments = true,
-
-                        RemoveContentControls = true,
-                        RemoveFieldCodes = true,
-
-                        RemoveGoBackBookmark = true,
-                        RemoveLastRenderedPageBreak = true,
-                        RemovePermissions = true,
-                        RemoveProof = true,
-                        RemoveSmartTags = true,
-                        RemoveSoftHyphens = true,
-                        RemoveHyperlinks = true
-                    };
-                    MarkupSimplifier.SimplifyMarkup(wDoc, msSettings);
-                    ChangeFootnoteEndnoteReferencesToUniqueRange(wDoc, startingIdForFootnotesEndnotes);
-                    AddUnidsToMarkupInContentParts(wDoc);
-                    AddFootnotesEndnotesParts(wDoc);
-                    FillInEmptyFootnotesEndnotes(wDoc);
-                }
-
-                return new WmlDocument(source.FileName, ms.ToArray());
-            }
-        }
-
-        private static void TestForInvalidContent(WordprocessingDocument wDoc)
-        {
-            foreach (OpenXmlPart part in wDoc.ContentParts())
-            {
-                XDocument xDoc = part.GetXDocument();
-                if (xDoc.Descendants(W.altChunk).Any())
-                    throw new OpenXmlPowerToolsException("Unsupported document, contains w:altChunk");
-                if (xDoc.Descendants(W.subDoc).Any())
-                    throw new OpenXmlPowerToolsException("Unsupported document, contains w:subDoc");
-                if (xDoc.Descendants(W.contentPart).Any())
-                    throw new OpenXmlPowerToolsException("Unsupported document, contains w:contentPart");
-            }
-        }
-
-        private static void RemoveExistingPowerToolsMarkup(WordprocessingDocument wDoc)
-        {
-            wDoc.MainDocumentPart
-                .GetXDocument()
-                .Root?
-                .Descendants()
-                .Attributes()
-                .Where(a => a.Name.Namespace == PtOpenXml.pt)
-                .Where(a => a.Name != PtOpenXml.Unid)
-                .Remove();
-
-            wDoc.MainDocumentPart.PutXDocument();
-
-            FootnotesPart fnPart = wDoc.MainDocumentPart.FootnotesPart;
-            if (fnPart != null)
-            {
-                XDocument fnXDoc = fnPart.GetXDocument();
-                fnXDoc
-                    .Root?
-                    .Descendants()
-                    .Attributes()
-                    .Where(a => a.Name.Namespace == PtOpenXml.pt)
-                    .Where(a => a.Name != PtOpenXml.Unid)
-                    .Remove();
-
-                fnPart.PutXDocument();
-            }
-
-            EndnotesPart enPart = wDoc.MainDocumentPart.EndnotesPart;
-            if (enPart != null)
-            {
-                XDocument enXDoc = enPart.GetXDocument();
-                enXDoc
-                    .Root?
-                    .Descendants()
-                    .Attributes()
-                    .Where(a => a.Name.Namespace == PtOpenXml.pt)
-                    .Where(a => a.Name != PtOpenXml.Unid)
-                    .Remove();
-
-                enPart.PutXDocument();
-            }
-        }
-
-        private static void ChangeFootnoteEndnoteReferencesToUniqueRange(
-            WordprocessingDocument wDoc,
-            int startingIdForFootnotesEndnotes)
-        {
-            MainDocumentPart mainDocPart = wDoc.MainDocumentPart;
-            FootnotesPart footnotesPart = wDoc.MainDocumentPart.FootnotesPart;
-            EndnotesPart endnotesPart = wDoc.MainDocumentPart.EndnotesPart;
-
-            XElement document =
-                mainDocPart.GetXDocument().Root ?? throw new OpenXmlPowerToolsException("Invalid document.");
-
-            XElement footnotes = footnotesPart?.GetXDocument().Root;
-            XElement endnotes = endnotesPart?.GetXDocument().Root;
-
-            IEnumerable<XElement> references = document
-                .Descendants()
-                .Where(d => d.Name == W.footnoteReference || d.Name == W.endnoteReference);
-
-            foreach (XElement r in references)
-            {
-                var oldId = (string) r.Attribute(W.id);
-                string newId = startingIdForFootnotesEndnotes.ToString();
-                startingIdForFootnotesEndnotes++;
-                r.SetAttributeValue(W.id, newId);
-                if (r.Name == W.footnoteReference)
-                {
-                    XElement fn = footnotes?
-                        .Elements()
-                        .FirstOrDefault(e => (string) e.Attribute(W.id) == oldId);
-
-                    if (fn == null)
-                    {
-                        throw new OpenXmlPowerToolsException("Invalid document");
-                    }
-
-                    fn.SetAttributeValue(W.id, newId);
-                }
-                else
-                {
-                    XElement en = endnotes?
-                        .Elements()
-                        .FirstOrDefault(e => (string) e.Attribute(W.id) == oldId);
-
-                    if (en == null)
-                    {
-                        throw new OpenXmlPowerToolsException("Invalid document");
-                    }
-
-                    en.SetAttributeValue(W.id, newId);
-                }
-            }
-
-            mainDocPart.PutXDocument();
-            footnotesPart?.PutXDocument();
-            endnotesPart?.PutXDocument();
-        }
-
-        private static void AddUnidsToMarkupInContentParts(WordprocessingDocument wDoc)
-        {
-            XDocument mdp = wDoc.MainDocumentPart.GetXDocument();
-            AssignUnidToAllElements(mdp.Root);
-            IgnorePt14Namespace(mdp.Root);
-            wDoc.MainDocumentPart.PutXDocument();
-
-            if (wDoc.MainDocumentPart.FootnotesPart != null)
-            {
-                XDocument p = wDoc.MainDocumentPart.FootnotesPart.GetXDocument();
-                AssignUnidToAllElements(p.Root);
-                IgnorePt14Namespace(p.Root);
-                wDoc.MainDocumentPart.FootnotesPart.PutXDocument();
-            }
-
-            if (wDoc.MainDocumentPart.EndnotesPart != null)
-            {
-                XDocument p = wDoc.MainDocumentPart.EndnotesPart.GetXDocument();
-                AssignUnidToAllElements(p.Root);
-                IgnorePt14Namespace(p.Root);
-                wDoc.MainDocumentPart.EndnotesPart.PutXDocument();
-            }
-        }
-
-        private static void AssignUnidToAllElements(XElement contentParent)
-        {
-            IEnumerable<XElement> content = contentParent.Descendants();
-            foreach (XElement d in content)
-            {
-                if (d.Attribute(PtOpenXml.Unid) == null)
-                {
-                    string unid = Guid.NewGuid().ToString().Replace("-", "");
-                    var newAtt = new XAttribute(PtOpenXml.Unid, unid);
-                    d.Add(newAtt);
-                }
-            }
-        }
-
-        [SuppressMessage("ReSharper", "CoVariantArrayConversion")]
-        private static void AddFootnotesEndnotesParts(WordprocessingDocument wDoc)
-        {
-            MainDocumentPart mdp = wDoc.MainDocumentPart;
-            if (mdp.FootnotesPart == null)
-            {
-                mdp.AddNewPart<FootnotesPart>();
-                XDocument newFootnotes = wDoc.MainDocumentPart.FootnotesPart.GetXDocument();
-                newFootnotes.Declaration.Standalone = "yes";
-                newFootnotes.Declaration.Encoding = "UTF-8";
-                newFootnotes.Add(new XElement(W.footnotes, NamespaceAttributes));
-                mdp.FootnotesPart.PutXDocument();
-            }
-
-            if (mdp.EndnotesPart == null)
-            {
-                mdp.AddNewPart<EndnotesPart>();
-                XDocument newEndnotes = wDoc.MainDocumentPart.EndnotesPart.GetXDocument();
-                newEndnotes.Declaration.Standalone = "yes";
-                newEndnotes.Declaration.Encoding = "UTF-8";
-                newEndnotes.Add(new XElement(W.endnotes, NamespaceAttributes));
-                mdp.EndnotesPart.PutXDocument();
-            }
-        }
-
-        private static void FillInEmptyFootnotesEndnotes(WordprocessingDocument wDoc)
-        {
-            XElement emptyFootnote = XElement.Parse(
-                @"<w:p xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-  <w:pPr>
-    <w:pStyle w:val='FootnoteText'/>
-  </w:pPr>
-  <w:r>
-    <w:rPr>
-      <w:rStyle w:val='FootnoteReference'/>
-    </w:rPr>
-    <w:footnoteRef/>
-  </w:r>
-</w:p>");
-
-            XElement emptyEndnote = XElement.Parse(
-                @"<w:p xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-  <w:pPr>
-    <w:pStyle w:val='EndnoteText'/>
-  </w:pPr>
-  <w:r>
-    <w:rPr>
-      <w:rStyle w:val='EndnoteReference'/>
-    </w:rPr>
-    <w:endnoteRef/>
-  </w:r>
-</w:p>");
-
-            FootnotesPart footnotePart = wDoc.MainDocumentPart.FootnotesPart;
-            if (footnotePart != null)
-            {
-                XElement fnRoot = footnotePart.GetXDocument().Root ?? throw new ArgumentException();
-                foreach (XElement fn in fnRoot.Elements(W.footnote))
-                {
-                    if (!fn.HasElements)
-                        fn.Add(emptyFootnote);
-                }
-
-                footnotePart.PutXDocument();
-            }
-
-            EndnotesPart endnotePart = wDoc.MainDocumentPart.EndnotesPart;
-            if (endnotePart != null)
-            {
-                XElement fnRoot = endnotePart.GetXDocument().Root ?? throw new ArgumentException();
-                foreach (XElement fn in fnRoot.Elements(W.endnote))
-                {
-                    if (!fn.HasElements)
-                        fn.Add(emptyEndnote);
-                }
-
-                endnotePart.PutXDocument();
-            }
-        }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 3232
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.Methods.ProduceDocument.cs


+ 0 - 103
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.Methods.Util.cs

@@ -1,103 +0,0 @@
-// 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.Generic;
-using System.IO;
-using System.IO.Packaging;
-using System.Linq;
-using System.Xml.Linq;
-
-namespace OpenXmlPowerTools
-{
-    public static partial class WmlComparer
-    {
-        private static XElement MoveRelatedPartsToDestination(
-            PackagePart partOfDeletedContent,
-            PackagePart partInNewDocument,
-            XElement contentElement)
-        {
-            List<XElement> elementsToUpdate = contentElement
-                .Descendants()
-                .Where(d => d.Attributes().Any(a => ComparisonUnitWord.RelationshipAttributeNames.Contains(a.Name)))
-                .ToList();
-
-            foreach (XElement element in elementsToUpdate)
-            {
-                List<XAttribute> attributesToUpdate = element
-                    .Attributes()
-                    .Where(a => ComparisonUnitWord.RelationshipAttributeNames.Contains(a.Name))
-                    .ToList();
-
-                foreach (XAttribute att in attributesToUpdate)
-                {
-                    var rId = (string) att;
-
-                    PackageRelationship relationshipForDeletedPart = partOfDeletedContent.GetRelationship(rId);
-
-                    Uri targetUri = PackUriHelper
-                        .ResolvePartUri(
-                            new Uri(partOfDeletedContent.Uri.ToString(), UriKind.Relative),
-                            relationshipForDeletedPart.TargetUri);
-
-                    PackagePart relatedPackagePart = partOfDeletedContent.Package.GetPart(targetUri);
-                    string[] uriSplit = relatedPackagePart.Uri.ToString().Split('/');
-                    string[] last = uriSplit[uriSplit.Length - 1].Split('.');
-                    string uriString;
-                    if (last.Length == 2)
-                    {
-                        uriString = uriSplit.SkipLast(1).Select(p => p + "/").StringConcatenate() +
-                                    "P" + Guid.NewGuid().ToString().Replace("-", "") + "." + last[1];
-                    }
-                    else
-                    {
-                        uriString = uriSplit.SkipLast(1).Select(p => p + "/").StringConcatenate() +
-                                    "P" + Guid.NewGuid().ToString().Replace("-", "");
-                    }
-
-                    Uri uri = relatedPackagePart.Uri.IsAbsoluteUri
-                        ? new Uri(uriString, UriKind.Absolute)
-                        : new Uri(uriString, UriKind.Relative);
-
-                    PackagePart newPart = partInNewDocument.Package.CreatePart(uri, relatedPackagePart.ContentType);
-
-                    // ReSharper disable once PossibleNullReferenceException
-                    using (Stream oldPartStream = relatedPackagePart.GetStream())
-                    using (Stream newPartStream = newPart.GetStream())
-                    {
-                        FileUtils.CopyStream(oldPartStream, newPartStream);
-                    }
-
-                    string newRid = "R" + Guid.NewGuid().ToString().Replace("-", "");
-                    partInNewDocument.CreateRelationship(newPart.Uri, TargetMode.Internal,
-                        relationshipForDeletedPart.RelationshipType, newRid);
-                    att.Value = newRid;
-
-                    if (newPart.ContentType.EndsWith("xml"))
-                    {
-                        XDocument newPartXDoc;
-                        using (Stream stream = newPart.GetStream())
-                        {
-                            newPartXDoc = XDocument.Load(stream);
-                            MoveRelatedPartsToDestination(relatedPackagePart, newPart, newPartXDoc.Root);
-                        }
-
-                        using (Stream stream = newPart.GetStream())
-                            newPartXDoc.Save(stream);
-                    }
-                }
-            }
-
-            return contentElement;
-        }
-
-        private static XAttribute GetXmlSpaceAttribute(string textOfTextElement)
-        {
-            if (char.IsWhiteSpace(textOfTextElement[0]) ||
-                char.IsWhiteSpace(textOfTextElement[textOfTextElement.Length - 1]))
-                return new XAttribute(XNamespace.Xml + "space", "preserve");
-
-            return null;
-        }
-    }
-}

+ 0 - 36
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Private.NestedTypes.cs

@@ -1,36 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-using System.Drawing;
-using System.Xml.Linq;
-
-namespace OpenXmlPowerTools
-{
-    public static partial class WmlComparer
-    {
-        private class Atgbw
-        {
-            public int? Key;
-            public ComparisonUnitAtom ComparisonUnitAtomMember;
-            public int NextIndex;
-        }
-
-        private class ConsolidationInfo
-        {
-            public string Revisor;
-            public Color Color;
-            public XElement RevisionElement;
-            public bool InsertBefore;
-            public string RevisionHash;
-            public XElement[] Footnotes;
-            public XElement[] Endnotes;
-            public string RevisionString; // for debugging purposes only
-        }
-
-        private class RecursionInfo
-        {
-            public XName ElementName;
-            public XName[] ChildElementPropertyNames;
-        }
-    }
-}

+ 0 - 227
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Public.Methods.Compare.cs

@@ -1,227 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-using System.IO;
-using System.Linq;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-
-// It is possible to optimize DescendantContentAtoms
-
-///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-// Currently, the unid is set at the beginning of the algorithm.  It is used by the code that establishes correlation
-// based on first rejecting// tracked revisions, then correlating paragraphs/tables.  It is requred for this algorithm
-// - after finding a correlated sequence in the document with rejected revisions, it uses the unid to find the same
-// paragraph in the document without rejected revisions, then sets the correlated sha1 hash in that document.
-//
-// But then when accepting tracked revisions, for certain paragraphs (where there are deleted paragraph marks) it is
-// going to lose the unids.  But this isn't a problem because when paragraph marks are deleted, the correlation is
-// definitely no longer possible.  Any paragraphs that are in a range of paragraphs that are coalesced can't be
-// correlated to paragraphs in the other document via their hash.  At that point we no longer care what their unids
-// are.
-//
-// But after that it is only used to reconstruct the tree.  It is also used in the debugging code that
-// prints the various correlated sequences and comparison units - this is display for debugging purposes only.
-///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-
-///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-// The key idea here is that a given paragraph will always have the same ancestors, and it doesn't matter whether the
-// content was deleted from the old document, inserted into the new document, or set as equal.  At this point, we
-// identify a paragraph as a sequential list of content atoms, terminated by a paragraph mark.  This entire list will
-// for a single paragraph, regardless of whether the paragraph is a child of the body, or if the paragraph is in a cell
-// in a table, or if the paragraph is in a text box.  The list of ancestors, from the paragraph to the root of the XML
-// tree will be the same for all content atoms in the paragraph.
-//
-// Therefore:
-//
-// Iterate through the list of content atoms backwards.  When the loop sees a paragraph mark, it gets the ancestor
-// unids from the paragraph mark to the top of the tree, and sets this as the same for all content atoms in the
-// paragraph.  For descendants of the paragraph mark, it doesn't really matter if content is put into separate runs
-// or what not.  We don't need to be concerned about what the unids are for descendants of the paragraph.
-///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-
-namespace OpenXmlPowerTools
-{
-    public static partial class WmlComparer
-    {
-        public static WmlDocument Compare(WmlDocument source1, WmlDocument source2, WmlComparerSettings settings)
-        {
-            return CompareInternal(source1, source2, settings, true);
-        }
-
-        private static WmlDocument CompareInternal(
-            WmlDocument source1,
-            WmlDocument source2,
-            WmlComparerSettings settings,
-            bool preProcessMarkupInOriginal)
-        {
-            if (preProcessMarkupInOriginal)
-            {
-                source1 = PreProcessMarkup(source1, settings.StartingIdForFootnotesEndnotes + 1000);
-            }
-
-            source2 = PreProcessMarkup(source2, settings.StartingIdForFootnotesEndnotes + 2000);
-
-            SaveDocumentIfDesired(source1, "Source1-Step1-PreProcess.docx", settings);
-            SaveDocumentIfDesired(source2, "Source2-Step1-PreProcess.docx", settings);
-
-            // at this point, both source1 and source2 have unid on every element.  These are the values that will
-            // enable reassembly of the XML tree.  But we need other values.
-
-            // In source1:
-            // - accept tracked revisions
-            // - determine hash code for every block-level element
-            // - save as attribute on every element
-
-            // - accept tracked revisions and reject tracked revisions leave the unids alone, where possible.
-            // - after accepting and calculating the hash, then can use the unids to find the right block-level
-            //   element in the unmodified source1, and install the hash
-
-            // In source2:
-            // - reject tracked revisions
-            // - determine hash code for every block-level element
-            // - save as an attribute on every element
-
-            // - after rejecting and calculating the hash, then can use the unids to find the right block-level element
-            //   in the unmodified source2, and install the hash
-
-            // - sometimes after accepting or rejecting tracked revisions, several paragraphs will get coalesced into a
-            //   single paragraph due to paragraph marks being inserted / deleted.
-            // - in this case, some paragraphs will not get a hash injected onto them.
-            // - if a paragraph doesn't have a hash, then it will never correspond to another paragraph, and such
-            //   issues will need to be resolved in the normal execution of the LCS algorithm.
-            // - note that when we do propagate the unid through for the first paragraph.
-
-            // Establish correlation between the two.
-            // Find the longest common sequence of block-level elements where hash codes are the same.
-            // this sometimes will be every block level element in the document.  Or sometimes will be just a fair
-            // number of them.
-
-            // at the start of doing the LCS algorithm, we will match up content, and put them in corresponding unknown
-            // correlated comparison units.  Those paragraphs will only ever be matched to their corresponding paragraph.
-            // then the algorithm can proceed as usual.
-
-            // need to call ChangeFootnoteEndnoteReferencesToUniqueRange before creating the wmlResult document, so that
-            // the same GUID ids are used for footnote and endnote references in both the 'after' document, and in the
-            // result document.
-
-            WmlDocument source1AfterAccepting = RevisionProcessor.AcceptRevisions(source1);
-            WmlDocument source2AfterRejecting = RevisionProcessor.RejectRevisions(source2);
-
-            SaveDocumentIfDesired(source1AfterAccepting, "Source1-Step2-AfterAccepting.docx", settings);
-            SaveDocumentIfDesired(source2AfterRejecting, "Source2-Step2-AfterRejecting.docx", settings);
-
-            // this creates the correlated hash codes that enable us to match up ranges of paragraphs based on
-            // accepting in source1, rejecting in source2
-            source1 = HashBlockLevelContent(source1, source1AfterAccepting, settings);
-            source2 = HashBlockLevelContent(source2, source2AfterRejecting, settings);
-
-            SaveDocumentIfDesired(source1, "Source1-Step3-AfterHashing.docx", settings);
-            SaveDocumentIfDesired(source2, "Source2-Step3-AfterHashing.docx", settings);
-
-            // Accept revisions in before, and after
-            source1 = RevisionProcessor.AcceptRevisions(source1);
-            source2 = RevisionProcessor.AcceptRevisions(source2);
-
-            SaveDocumentIfDesired(source1, "Source1-Step4-AfterAccepting.docx", settings);
-            SaveDocumentIfDesired(source2, "Source2-Step4-AfterAccepting.docx", settings);
-
-            // after accepting revisions, some unids may have been removed by revision accepter, along with the
-            // correlatedSHA1Hash codes, this is as it should be.
-            // but need to go back in and add guids to paragraphs that have had them removed.
-
-            using (var ms = new MemoryStream())
-            {
-                ms.Write(source2.DocumentByteArray, 0, source2.DocumentByteArray.Length);
-                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
-                {
-                    AddUnidsToMarkupInContentParts(wDoc);
-                }
-            }
-
-            var wmlResult = new WmlDocument(source1);
-            using (var ms1 = new MemoryStream())
-            using (var ms2 = new MemoryStream())
-            {
-                ms1.Write(source1.DocumentByteArray, 0, source1.DocumentByteArray.Length);
-                ms2.Write(source2.DocumentByteArray, 0, source2.DocumentByteArray.Length);
-                WmlDocument producedDocument;
-
-                using (WordprocessingDocument wDoc1 = WordprocessingDocument.Open(ms1, true))
-                using (WordprocessingDocument wDoc2 = WordprocessingDocument.Open(ms2, true))
-                {
-                    producedDocument = ProduceDocumentWithTrackedRevisions(settings, wmlResult, wDoc1, wDoc2);
-                }
-
-                SaveDocumentsAfterProducingDocument(ms1, ms2, settings);
-                SaveCleanedDocuments(source1, producedDocument, settings);
-
-                return producedDocument;
-            }
-        }
-
-        private static void SaveDocumentIfDesired(WmlDocument source, string name, WmlComparerSettings settings)
-        {
-            if (SaveIntermediateFilesForDebugging && settings.DebugTempFileDi != null)
-            {
-                var fileInfo = new FileInfo(Path.Combine(settings.DebugTempFileDi.FullName, name));
-                source.SaveAs(fileInfo.FullName);
-            }
-        }
-
-        private static void SaveDocumentsAfterProducingDocument(MemoryStream ms1, MemoryStream ms2, WmlComparerSettings settings)
-        {
-            if (SaveIntermediateFilesForDebugging && settings.DebugTempFileDi != null)
-            {
-                SaveDocumentIfDesired(new WmlDocument("after1.docx", ms1), "Source1-Step5-AfterProducingDocument.docx", settings);
-                SaveDocumentIfDesired(new WmlDocument("after2.docx", ms2), "Source2-Step5-AfterProducingDocument.docx", settings);
-            }
-        }
-
-        private static void SaveCleanedDocuments(WmlDocument source1, WmlDocument producedDocument, WmlComparerSettings settings)
-        {
-            if (SaveIntermediateFilesForDebugging && settings.DebugTempFileDi != null)
-            {
-                WmlDocument cleanedSource = CleanPowerToolsAndRsid(source1);
-                SaveDocumentIfDesired(cleanedSource, "Cleaned-Source.docx", settings);
-
-                WmlDocument cleanedProduced = CleanPowerToolsAndRsid(producedDocument);
-                SaveDocumentIfDesired(cleanedProduced, "Cleaned-Produced.docx", settings);
-            }
-        }
-
-        private static WmlDocument CleanPowerToolsAndRsid(WmlDocument producedDocument)
-        {
-            using (var ms = new MemoryStream())
-            {
-                ms.Write(producedDocument.DocumentByteArray, 0, producedDocument.DocumentByteArray.Length);
-                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
-                {
-                    foreach (OpenXmlPart cp in wDoc.ContentParts())
-                    {
-                        XDocument xd = cp.GetXDocument();
-                        object newRoot = CleanPartTransform(xd.Root);
-                        xd.Root?.ReplaceWith(newRoot);
-                        cp.PutXDocument();
-                    }
-                }
-
-                var cleaned = new WmlDocument("cleaned.docx", ms.ToArray());
-                return cleaned;
-            }
-        }
-
-        private static object CleanPartTransform(XNode node)
-        {
-            if (node is XElement element)
-            {
-                return new XElement(element.Name,
-                    element.Attributes().Where(a => a.Name.Namespace != PtOpenXml.pt &&
-                                                    !a.Name.LocalName.ToLower().Contains("rsid")),
-                    element.Nodes().Select(CleanPartTransform));
-            }
-
-            return node;
-        }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 1002
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Public.Methods.Consolidate.cs


+ 0 - 214
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Public.Methods.GetRevisions.cs

@@ -1,214 +0,0 @@
-// 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.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public static partial class WmlComparer
-    {
-        // the following gets a flattened list of ComparisonUnitAtoms, with status indicated in each ComparisonUnitAtom: Deleted, Inserted, or Equal
-
-        // for any deleted or inserted rows, we go into the w:trPr properties, and add the appropriate w:ins or w:del element, and therefore
-        // when generating the document, the appropriate row will be marked as deleted or inserted.
-
-        public static List<WmlComparerRevision> GetRevisions(WmlDocument source, WmlComparerSettings settings)
-        {
-            using (var ms = new MemoryStream())
-            {
-                ms.Write(source.DocumentByteArray, 0, source.DocumentByteArray.Length);
-                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
-                {
-                    TestForInvalidContent(wDoc);
-                    RemoveExistingPowerToolsMarkup(wDoc);
-
-                    XElement contentParent = wDoc.MainDocumentPart.GetXDocument().Root?.Element(W.body);
-                    ComparisonUnitAtom[] atomList =
-                        CreateComparisonUnitAtomList(wDoc.MainDocumentPart, contentParent, settings).ToArray();
-
-                    if (False)
-                    {
-                        var sb = new StringBuilder();
-                        foreach (ComparisonUnitAtom item in atomList)
-                            sb.Append(item + Environment.NewLine);
-                        string sbs = sb.ToString();
-                        TestUtil.NotePad(sbs);
-                    }
-
-                    List<IGrouping<string, ComparisonUnitAtom>> grouped = atomList
-                        .GroupAdjacent(a =>
-                        {
-                            string key = a.CorrelationStatus.ToString();
-                            if (a.CorrelationStatus != CorrelationStatus.Equal)
-                            {
-                                var rt = new XElement(a.RevTrackElement.Name,
-                                    new XAttribute(XNamespace.Xmlns + "w",
-                                        "http://schemas.openxmlformats.org/wordprocessingml/2006/main"),
-                                    a.RevTrackElement.Attributes().Where(a2 => a2.Name != W.id && a2.Name != PtOpenXml.Unid));
-                                key += rt.ToString(SaveOptions.DisableFormatting);
-                            }
-
-                            return key;
-                        })
-                        .ToList();
-
-                    List<IGrouping<string, ComparisonUnitAtom>> revisions = grouped
-                        .Where(k => k.Key != "Equal")
-                        .ToList();
-
-                    if (False)
-                    {
-                        var sb = new StringBuilder();
-                        foreach (IGrouping<string, ComparisonUnitAtom> item in revisions)
-                        {
-                            sb.Append(item.Key + Environment.NewLine);
-                        }
-
-                        string sbs = sb.ToString();
-                        TestUtil.NotePad(sbs);
-                    }
-
-                    List<WmlComparerRevision> mainDocPartRevisionList = revisions
-                        .Select(rg =>
-                        {
-                            var rev = new WmlComparerRevision();
-                            if (rg.Key.StartsWith("Inserted"))
-                            {
-                                rev.RevisionType = WmlComparerRevisionType.Inserted;
-                            }
-                            else if (rg.Key.StartsWith("Deleted"))
-                            {
-                                rev.RevisionType = WmlComparerRevisionType.Deleted;
-                            }
-
-                            XElement revTrackElement = rg.First().RevTrackElement;
-                            rev.RevisionXElement = revTrackElement;
-                            rev.Author = (string) revTrackElement.Attribute(W.author);
-                            rev.ContentXElement = rg.First().ContentElement;
-                            rev.Date = (string) revTrackElement.Attribute(W.date);
-                            rev.PartUri = wDoc.MainDocumentPart.Uri;
-                            rev.PartContentType = wDoc.MainDocumentPart.ContentType;
-
-                            if (!RevElementsWithNoText.Contains(rev.ContentXElement.Name))
-                            {
-                                rev.Text = rg
-                                    .Select(rgc => rgc.ContentElement.Name == W.pPr ? NewLine : rgc.ContentElement.Value)
-                                    .StringConcatenate();
-                            }
-
-                            return rev;
-                        })
-                        .ToList();
-
-                    IEnumerable<WmlComparerRevision> footnotesRevisionList =
-                        GetFootnoteEndnoteRevisionList(wDoc.MainDocumentPart.FootnotesPart, W.footnote, settings);
-                    IEnumerable<WmlComparerRevision> endnotesRevisionList =
-                        GetFootnoteEndnoteRevisionList(wDoc.MainDocumentPart.EndnotesPart, W.endnote, settings);
-
-                    List<WmlComparerRevision> finalRevisionList = mainDocPartRevisionList
-                        .Concat(footnotesRevisionList)
-                        .Concat(endnotesRevisionList)
-                        .ToList();
-
-                    return finalRevisionList;
-                }
-            }
-        }
-
-        private static IEnumerable<WmlComparerRevision> GetFootnoteEndnoteRevisionList(
-            OpenXmlPart footnotesEndnotesPart,
-            XName footnoteEndnoteElementName,
-            WmlComparerSettings settings)
-        {
-            if (footnotesEndnotesPart == null)
-            {
-                return Enumerable.Empty<WmlComparerRevision>();
-            }
-
-            XDocument xDoc = footnotesEndnotesPart.GetXDocument();
-            IEnumerable<XElement> footnotesEndnotes =
-                xDoc.Root?.Elements(footnoteEndnoteElementName) ?? throw new OpenXmlPowerToolsException("Invalid document.");
-
-            var revisionsForPart = new List<WmlComparerRevision>();
-            foreach (XElement fn in footnotesEndnotes)
-            {
-                ComparisonUnitAtom[] atomList = CreateComparisonUnitAtomList(footnotesEndnotesPart, fn, settings).ToArray();
-
-                if (False)
-                {
-                    var sb = new StringBuilder();
-                    foreach (ComparisonUnitAtom item in atomList)
-                    {
-                        sb.Append(item + Environment.NewLine);
-                    }
-
-                    string sbs = sb.ToString();
-                    TestUtil.NotePad(sbs);
-                }
-
-                List<IGrouping<string, ComparisonUnitAtom>> grouped = atomList
-                    .GroupAdjacent(a =>
-                    {
-                        string key = a.CorrelationStatus.ToString();
-                        if (a.CorrelationStatus != CorrelationStatus.Equal)
-                        {
-                            var rt = new XElement(a.RevTrackElement.Name,
-                                new XAttribute(XNamespace.Xmlns + "w",
-                                    "http://schemas.openxmlformats.org/wordprocessingml/2006/main"),
-                                a.RevTrackElement.Attributes().Where(a2 => a2.Name != W.id && a2.Name != PtOpenXml.Unid));
-
-                            key += rt.ToString(SaveOptions.DisableFormatting);
-                        }
-
-                        return key;
-                    })
-                    .ToList();
-
-                List<IGrouping<string, ComparisonUnitAtom>> revisions = grouped
-                    .Where(k => k.Key != "Equal")
-                    .ToList();
-
-                IEnumerable<WmlComparerRevision> thisNoteRevisionList = revisions
-                    .Select(rg =>
-                    {
-                        var rev = new WmlComparerRevision();
-                        if (rg.Key.StartsWith("Inserted"))
-                        {
-                            rev.RevisionType = WmlComparerRevisionType.Inserted;
-                        }
-                        else if (rg.Key.StartsWith("Deleted"))
-                        {
-                            rev.RevisionType = WmlComparerRevisionType.Deleted;
-                        }
-
-                        XElement revTrackElement = rg.First().RevTrackElement;
-                        rev.RevisionXElement = revTrackElement;
-                        rev.Author = (string) revTrackElement.Attribute(W.author);
-                        rev.ContentXElement = rg.First().ContentElement;
-                        rev.Date = (string) revTrackElement.Attribute(W.date);
-                        rev.PartUri = footnotesEndnotesPart.Uri;
-                        rev.PartContentType = footnotesEndnotesPart.ContentType;
-
-                        if (!RevElementsWithNoText.Contains(rev.ContentXElement.Name))
-                        {
-                            rev.Text = rg
-                                .Select(rgc => rgc.ContentElement.Name == W.pPr ? NewLine : rgc.ContentElement.Value)
-                                .StringConcatenate();
-                        }
-
-                        return rev;
-                    });
-
-                revisionsForPart.AddRange(thisNoteRevisionList);
-            }
-
-            return revisionsForPart;
-        }
-    }
-}

+ 0 - 29
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparer.Public.NestedTypes.cs

@@ -1,29 +0,0 @@
-// 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.Xml.Linq;
-
-namespace OpenXmlPowerTools
-{
-    public static partial class WmlComparer
-    {
-        public class WmlComparerRevision
-        {
-            public WmlComparerRevisionType RevisionType;
-            public string Text;
-            public string Author;
-            public string Date;
-            public XElement ContentXElement;
-            public XElement RevisionXElement;
-            public Uri PartUri;
-            public string PartContentType;
-        }
-
-        public enum WmlComparerRevisionType
-        {
-            Inserted,
-            Deleted
-        }
-    }
-}

+ 0 - 10
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparerConsolidateSettings.cs

@@ -1,10 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-namespace OpenXmlPowerTools
-{
-    public class WmlComparerConsolidateSettings
-    {
-        public bool ConsolidateWithTable = true;
-    }
-}

+ 0 - 27
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparerExtensions.cs

@@ -1,27 +0,0 @@
-// 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.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public static class WmlComparerExtensions
-    {
-        public static XElement GetMainDocumentBody(this WordprocessingDocument wordDocument)
-        {
-            return wordDocument.GetMainDocumentRoot().Element(W.body) ?? throw new ArgumentException("Invalid document.");
-        }
-
-        public static XElement GetMainDocumentRoot(this WordprocessingDocument wordDocument)
-        {
-            return wordDocument.MainDocumentPart?.GetXElement() ?? throw new ArgumentException("Invalid document.");
-        }
-
-        public static XElement GetXElement(this OpenXmlPart part)
-        {
-            return part.GetXDocument()?.Root ?? throw new ArgumentException("Invalid document.");
-        }
-    }
-}

+ 0 - 29
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparerSettings.cs

@@ -1,29 +0,0 @@
-// 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.Globalization;
-using System.IO;
-
-namespace OpenXmlPowerTools
-{
-    public class WmlComparerSettings
-    {
-        public char[] WordSeparators;
-        public string AuthorForRevisions = "Open-Xml-PowerTools";
-        public string DateTimeForRevisions = DateTime.Now.ToString("o");
-        public double DetailThreshold = 0.15;
-        public bool CaseInsensitive = false;
-        public CultureInfo CultureInfo = null;
-        public Action<string> LogCallback = null;
-        public int StartingIdForFootnotesEndnotes = 1;
-
-        public DirectoryInfo DebugTempFileDi;
-
-        public WmlComparerSettings()
-        {
-            // note that , and . are processed explicitly to handle cases where they are in a number or word
-            WordSeparators = new[] { ' ', '-', ')', '(', ';', ',' }; // todo need to fix this for complete list
-        }
-    }
-}

+ 0 - 59
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlComparerUtil.cs

@@ -1,59 +0,0 @@
-// 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.Security.Cryptography;
-using System.Text;
-
-namespace OpenXmlPowerTools
-{
-    internal static class WmlComparerUtil
-    {
-        public static string SHA1HashStringForUTF8String(string s)
-        {
-            var bytes = Encoding.UTF8.GetBytes(s);
-            var sha1 = SHA1.Create();
-            var hashBytes = sha1.ComputeHash(bytes);
-            return HexStringFromBytes(hashBytes);
-        }
-
-        public static string SHA1HashStringForByteArray(byte[] bytes)
-        {
-            var sha1 = SHA1.Create();
-            var hashBytes = sha1.ComputeHash(bytes);
-            return HexStringFromBytes(hashBytes);
-        }
-
-        public static string HexStringFromBytes(byte[] bytes)
-        {
-            var sb = new StringBuilder();
-            foreach (var b in bytes)
-            {
-                var hex = b.ToString("x2");
-                sb.Append(hex);
-            }
-
-            return sb.ToString();
-        }
-
-        public static ComparisonUnitGroupType ComparisonUnitGroupTypeFromLocalName(string localName)
-        {
-            switch (localName)
-            {
-                case "p":
-                    return ComparisonUnitGroupType.Paragraph;
-                case "tbl":
-                    return ComparisonUnitGroupType.Table;
-                case "tr":
-                    return ComparisonUnitGroupType.Row;
-                case "tc":
-                    return ComparisonUnitGroupType.Cell;
-                case "txbxContent":
-                    return ComparisonUnitGroupType.Textbox;
-                default:
-                    throw new ArgumentOutOfRangeException(nameof(localName),
-                        $@"Unsupported localName: '{localName}'.");
-            }
-        }
-    }
-}

+ 0 - 14
TEAMModelOS.SDK/Module/OpenXmlTool/Comparer/WmlRevisedDocumentInfo.cs

@@ -1,14 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-using System.Drawing;
-
-namespace OpenXmlPowerTools
-{
-    public class WmlRevisedDocumentInfo
-    {
-        public WmlDocument RevisedDocument;
-        public string Revisor;
-        public Color Color;
-    }
-}

+ 0 - 857
TEAMModelOS.SDK/Module/OpenXmlTool/DocumentAssembler.cs

@@ -1,857 +0,0 @@
-// 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.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Xml;
-using System.Xml.Linq;
-using System.Xml.XPath;
-using System.Xml.Schema;
-using DocumentFormat.OpenXml.Office.CustomUI;
-using DocumentFormat.OpenXml.Packaging;
-using OpenXmlPowerTools;
-using System.Collections;
-
-namespace OpenXmlPowerTools
-{
-    public class DocumentAssembler
-    {
-        public static WmlDocument AssembleDocument(WmlDocument templateDoc, XmlDocument data, out bool templateError)
-        {
-            XDocument xDoc = data.GetXDocument();
-            return AssembleDocument(templateDoc, xDoc.Root, out templateError);
-        }
-
-        public static WmlDocument AssembleDocument(WmlDocument templateDoc, XElement data, out bool templateError)
-        {
-            byte[] byteArray = templateDoc.DocumentByteArray;
-            using (MemoryStream mem = new MemoryStream())
-            {
-                mem.Write(byteArray, 0, (int)byteArray.Length);
-                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(mem, true))
-                {
-                    if (RevisionAccepter.HasTrackedRevisions(wordDoc))
-                        throw new OpenXmlPowerToolsException("Invalid DocumentAssembler template - contains tracked revisions");
-
-                    var te = new TemplateError();
-                    foreach (var part in wordDoc.ContentParts())
-                    {
-                        ProcessTemplatePart(data, te, part);
-                    }
-                    templateError = te.HasError;
-                }
-                WmlDocument assembledDocument = new WmlDocument("TempFileName.docx", mem.ToArray());
-                return assembledDocument;
-            }
-        }
-
-        private static void ProcessTemplatePart(XElement data, TemplateError te, OpenXmlPart part)
-        {
-            XDocument xDoc = part.GetXDocument();
-
-            var xDocRoot = RemoveGoBackBookmarks(xDoc.Root);
-
-            // content controls in cells can surround the W.tc element, so transform so that such content controls are within the cell content
-            xDocRoot = (XElement)NormalizeContentControlsInCells(xDocRoot);
-
-            xDocRoot = (XElement)TransformToMetadata(xDocRoot, data, te);
-
-            // Table might have been placed at run-level, when it should be at block-level, so fix this.
-            // Repeat, EndRepeat, Conditional, EndConditional are allowed at run level, but only if there is a matching pair
-            // if there is only one Repeat, EndRepeat, Conditional, EndConditional, then move to block level.
-            // if there is a matching pair, then is OK.
-            xDocRoot = (XElement)ForceBlockLevelAsAppropriate(xDocRoot, te);
-
-            NormalizeTablesRepeatAndConditional(xDocRoot, te);
-
-            // any EndRepeat, EndConditional that remain are orphans, so replace with an error
-            ProcessOrphanEndRepeatEndConditional(xDocRoot, te);
-
-            // do the actual content replacement
-            xDocRoot = (XElement)ContentReplacementTransform(xDocRoot, data, te);
-
-            xDoc.Elements().First().ReplaceWith(xDocRoot);
-            part.PutXDocument();
-            return;
-        }
-
-        private static XName[] s_MetaToForceToBlock = new XName[] {
-            PA.Conditional,
-            PA.EndConditional,
-            PA.Repeat,
-            PA.EndRepeat,
-            PA.Table,
-        };
-
-        private static object ForceBlockLevelAsAppropriate(XNode node, TemplateError te)
-        {
-            XElement element = node as XElement;
-            if (element != null)
-            {
-                if (element.Name == W.p)
-                {
-                    var childMeta = element.Elements().Where(n => s_MetaToForceToBlock.Contains(n.Name)).ToList();
-                    if (childMeta.Count() == 1)
-                    {
-                        var child = childMeta.First();
-                        var otherTextInParagraph = element.Elements(W.r).Elements(W.t).Select(t => (string)t).StringConcatenate().Trim();
-                        if (otherTextInParagraph != "")
-                        {
-                            var newPara = new XElement(element);
-                            var newMeta = newPara.Elements().Where(n => s_MetaToForceToBlock.Contains(n.Name)).First();
-                            newMeta.ReplaceWith(CreateRunErrorMessage("Error: Unmatched metadata can't be in paragraph with other text", te));
-                            return newPara;
-                        }
-                        var meta = new XElement(child.Name,
-                            child.Attributes(),
-                            new XElement(W.p,
-                                element.Attributes(),
-                                element.Elements(W.pPr),
-                                child.Elements()));
-                        return meta;
-                    }
-                    var count = childMeta.Count();
-                    if (count % 2 == 0)
-                    {
-                        if (childMeta.Where(c => c.Name == PA.Repeat).Count() != childMeta.Where(c => c.Name == PA.EndRepeat).Count())
-                            return CreateContextErrorMessage(element, "Error: Mismatch Repeat / EndRepeat at run level", te);
-                        if (childMeta.Where(c => c.Name == PA.Conditional).Count() != childMeta.Where(c => c.Name == PA.EndConditional).Count())
-                            return CreateContextErrorMessage(element, "Error: Mismatch Conditional / EndConditional at run level", te);
-                        return new XElement(element.Name,
-                            element.Attributes(),
-                            element.Nodes().Select(n => ForceBlockLevelAsAppropriate(n, te)));
-                    }
-                    else
-                    {
-                        return CreateContextErrorMessage(element, "Error: Invalid metadata at run level", te);
-                    }
-                }
-                return new XElement(element.Name,
-                    element.Attributes(),
-                    element.Nodes().Select(n => ForceBlockLevelAsAppropriate(n, te)));
-            }
-            return node;
-        }
-
-        private static void ProcessOrphanEndRepeatEndConditional(XElement xDocRoot, TemplateError te)
-        {
-            foreach (var element in xDocRoot.Descendants(PA.EndRepeat).ToList())
-            {
-                var error = CreateContextErrorMessage(element, "Error: EndRepeat without matching Repeat", te);
-                element.ReplaceWith(error);
-            }
-            foreach (var element in xDocRoot.Descendants(PA.EndConditional).ToList())
-            {
-                var error = CreateContextErrorMessage(element, "Error: EndConditional without matching Conditional", te);
-                element.ReplaceWith(error);
-            }
-        }
-
-        private static XElement RemoveGoBackBookmarks(XElement xElement)
-        {
-            var cloneXDoc = new XElement(xElement);
-            while (true)
-            {
-                var bm = cloneXDoc.DescendantsAndSelf(W.bookmarkStart).FirstOrDefault(b => (string)b.Attribute(W.name) == "_GoBack");
-                if (bm == null)
-                    break;
-                var id = (string)bm.Attribute(W.id);
-                var endBm = cloneXDoc.DescendantsAndSelf(W.bookmarkEnd).FirstOrDefault(b => (string)b.Attribute(W.id) == id);
-                bm.Remove();
-                endBm.Remove();
-            }
-            return cloneXDoc;
-        }
-
-        // this transform inverts content controls that surround W.tc elements.  After transforming, the W.tc will contain
-        // the content control, which contains the paragraph content of the cell.
-        private static object NormalizeContentControlsInCells(XNode node)
-        {
-            XElement element = node as XElement;
-            if (element != null)
-            {
-                if (element.Name == W.sdt && element.Parent.Name == W.tr)
-                {
-                    var newCell = new XElement(W.tc,
-                        element.Elements(W.tc).Elements(W.tcPr),
-                        new XElement(W.sdt,
-                            element.Elements(W.sdtPr),
-                            element.Elements(W.sdtEndPr),
-                            new XElement(W.sdtContent,
-                                element.Elements(W.sdtContent).Elements(W.tc).Elements().Where(e => e.Name != W.tcPr))));
-                    return newCell;
-                }
-                return new XElement(element.Name,
-                    element.Attributes(),
-                    element.Nodes().Select(n => NormalizeContentControlsInCells(n)));
-            }
-            return node;
-        }
-
-        // The following method is written using tree modification, not RPFT, because it is easier to write in this fashion.
-        // These types of operations are not as easy to write using RPFT.
-        // Unless you are completely clear on the semantics of LINQ to XML DML, do not make modifications to this method.
-        private static void NormalizeTablesRepeatAndConditional(XElement xDoc, TemplateError te)
-        {
-            var tables = xDoc.Descendants(PA.Table).ToList();
-            foreach (var table in tables)
-            {
-                var followingElement = table.ElementsAfterSelf().Where(e => e.Name == W.tbl || e.Name == W.p).FirstOrDefault();
-                if (followingElement == null || followingElement.Name != W.tbl)
-                {
-                    table.ReplaceWith(CreateParaErrorMessage("Table metadata is not immediately followed by a table", te));
-                    continue;
-                }
-                // remove superflous paragraph from Table metadata
-                table.RemoveNodes();
-                // detach w:tbl from parent, and add to Table metadata
-                followingElement.Remove();
-                table.Add(followingElement);
-            }
-
-            int repeatDepth = 0;
-            int conditionalDepth = 0;
-            foreach (var metadata in xDoc.Descendants().Where(d =>
-                    d.Name == PA.Repeat ||
-                    d.Name == PA.Conditional ||
-                    d.Name == PA.EndRepeat ||
-                    d.Name == PA.EndConditional))
-            {
-                if (metadata.Name == PA.Repeat)
-                {
-                    ++repeatDepth;
-                    metadata.Add(new XAttribute(PA.Depth, repeatDepth));
-                    continue;
-                }
-                if (metadata.Name == PA.EndRepeat)
-                {
-                    metadata.Add(new XAttribute(PA.Depth, repeatDepth));
-                    --repeatDepth;
-                    continue;
-                }
-                if (metadata.Name == PA.Conditional)
-                {
-                    ++conditionalDepth;
-                    metadata.Add(new XAttribute(PA.Depth, conditionalDepth));
-                    continue;
-                }
-                if (metadata.Name == PA.EndConditional)
-                {
-                    metadata.Add(new XAttribute(PA.Depth, conditionalDepth));
-                    --conditionalDepth;
-                    continue;
-                }
-            }
-
-            while (true)
-            {
-                bool didReplace = false;
-                foreach (var metadata in xDoc.Descendants().Where(d => (d.Name == PA.Repeat || d.Name == PA.Conditional) && d.Attribute(PA.Depth) != null).ToList())
-                {
-                    var depth = (int)metadata.Attribute(PA.Depth);
-                    XName matchingEndName = null;
-                    if (metadata.Name == PA.Repeat)
-                        matchingEndName = PA.EndRepeat;
-                    else if (metadata.Name == PA.Conditional)
-                        matchingEndName = PA.EndConditional;
-                    if (matchingEndName == null)
-                        throw new OpenXmlPowerToolsException("Internal error");
-                    var matchingEnd = metadata.ElementsAfterSelf(matchingEndName).FirstOrDefault(end => { return (int)end.Attribute(PA.Depth) == depth; });
-                    if (matchingEnd == null)
-                    {
-                        metadata.ReplaceWith(CreateParaErrorMessage(string.Format("{0} does not have matching {1}", metadata.Name.LocalName, matchingEndName.LocalName), te));
-                        continue;
-                    }
-                    metadata.RemoveNodes();
-                    var contentBetween = metadata.ElementsAfterSelf().TakeWhile(after => after != matchingEnd).ToList();
-                    foreach (var item in contentBetween)
-                        item.Remove();
-                    contentBetween = contentBetween.Where(n => n.Name != W.bookmarkStart && n.Name != W.bookmarkEnd).ToList();
-                    metadata.Add(contentBetween);
-                    metadata.Attributes(PA.Depth).Remove();
-                    matchingEnd.Remove();
-                    didReplace = true;
-                    break;
-                }
-                if (!didReplace)
-                    break;
-            }
-        }
-
-        private static List<string> s_AliasList = new List<string>()
-        {
-            "Content",
-            "Table",
-            "Repeat",
-            "EndRepeat",
-            "Conditional",
-            "EndConditional",
-        };
-
-        private static object TransformToMetadata(XNode node, XElement data, TemplateError te)
-        {
-            XElement element = node as XElement;
-            if (element != null)
-            {
-                if (element.Name == W.sdt)
-                {
-                    var alias = (string)element.Elements(W.sdtPr).Elements(W.alias).Attributes(W.val).FirstOrDefault();
-                    if (alias == null || alias == "" || s_AliasList.Contains(alias))
-                    {
-                        var ccContents = element
-                            .DescendantsTrimmed(W.txbxContent)
-                            .Where(e => e.Name == W.t)
-                            .Select(t => (string)t)
-                            .StringConcatenate()
-                            .Trim()
-                            .Replace('“', '"')
-                            .Replace('”', '"');
-                        if (ccContents.StartsWith("<"))
-                        {
-                            XElement xml = TransformXmlTextToMetadata(te, ccContents);
-                            if (xml.Name == W.p || xml.Name == W.r)  // this means there was an error processing the XML.
-                            {
-                                if (element.Parent.Name == W.p)
-                                    return xml.Elements(W.r);
-                                return xml;
-                            }
-                            if (alias != null && xml.Name.LocalName != alias)
-                            {
-                                if (element.Parent.Name == W.p)
-                                    return CreateRunErrorMessage("Error: Content control alias does not match metadata element name", te);
-                                else
-                                    return CreateParaErrorMessage("Error: Content control alias does not match metadata element name", te);
-                            }
-                            xml.Add(element.Elements(W.sdtContent).Elements());
-                            return xml;
-                        }
-                        return new XElement(element.Name,
-                            element.Attributes(),
-                            element.Nodes().Select(n => TransformToMetadata(n, data, te)));
-                    }
-                    return new XElement(element.Name,
-                        element.Attributes(),
-                        element.Nodes().Select(n => TransformToMetadata(n, data, te)));
-                }
-                if (element.Name == W.p)
-                {
-                    var paraContents = element
-                        .DescendantsTrimmed(W.txbxContent)
-                        .Where(e => e.Name == W.t)
-                        .Select(t => (string)t)
-                        .StringConcatenate()
-                        .Trim();
-                    int occurances = paraContents.Select((c, i) => paraContents.Substring(i)).Count(sub => sub.StartsWith("<#"));
-                    if (paraContents.StartsWith("<#") && paraContents.EndsWith("#>") && occurances == 1)
-                    {
-                        var xmlText = paraContents.Substring(2, paraContents.Length - 4).Trim();
-                        XElement xml = TransformXmlTextToMetadata(te, xmlText);
-                        if (xml.Name == W.p || xml.Name == W.r)
-                            return xml;
-                        xml.Add(element);
-                        return xml;
-                    }
-                    if (paraContents.Contains("<#"))
-                    {
-                        List<RunReplacementInfo> runReplacementInfo = new List<RunReplacementInfo>();
-                        var thisGuid = Guid.NewGuid().ToString();
-                        var r = new Regex("<#.*?#>");
-                        XElement xml = null;
-                        OpenXmlRegex.Replace(new[] { element }, r, thisGuid, (para, match) =>
-                        {
-                            var matchString = match.Value.Trim();
-                            var xmlText = matchString.Substring(2, matchString.Length - 4).Trim().Replace('“', '"').Replace('”', '"');
-                            try
-                            {
-                                xml = XElement.Parse(xmlText);
-                            }
-                            catch (XmlException e)
-                            {
-                                RunReplacementInfo rri = new RunReplacementInfo()
-                                {
-                                    Xml = null,
-                                    XmlExceptionMessage = "XmlException: " + e.Message,
-                                    SchemaValidationMessage = null,
-                                };
-                                runReplacementInfo.Add(rri);
-                                return true;
-                            }
-                            string schemaError = ValidatePerSchema(xml);
-                            if (schemaError != null)
-                            {
-                                RunReplacementInfo rri = new RunReplacementInfo()
-                                {
-                                    Xml = null,
-                                    XmlExceptionMessage = null,
-                                    SchemaValidationMessage = "Schema Validation Error: " + schemaError,
-                                };
-                                runReplacementInfo.Add(rri);
-                                return true;
-                            }
-                            RunReplacementInfo rri2 = new RunReplacementInfo()
-                            {
-                                Xml = xml,
-                                XmlExceptionMessage = null,
-                                SchemaValidationMessage = null,
-                            };
-                            runReplacementInfo.Add(rri2);
-                            return true;
-                        }, false);
-
-                        var newPara = new XElement(element);
-                        foreach (var rri in runReplacementInfo)
-                        {
-                            var runToReplace = newPara.Descendants(W.r).FirstOrDefault(rn => rn.Value == thisGuid && rn.Parent.Name != PA.Content);
-                            if (runToReplace == null)
-                                throw new OpenXmlPowerToolsException("Internal error");
-                            if (rri.XmlExceptionMessage != null)
-                                runToReplace.ReplaceWith(CreateRunErrorMessage(rri.XmlExceptionMessage, te));
-                            else if (rri.SchemaValidationMessage != null)
-                                runToReplace.ReplaceWith(CreateRunErrorMessage(rri.SchemaValidationMessage, te));
-                            else
-                            {
-                                var newXml = new XElement(rri.Xml);
-                                newXml.Add(runToReplace);
-                                runToReplace.ReplaceWith(newXml);
-                            }
-                        }
-                        var coalescedParagraph = WordprocessingMLUtil.CoalesceAdjacentRunsWithIdenticalFormatting(newPara);
-                        return coalescedParagraph;
-                    }
-                }
-
-                return new XElement(element.Name,
-                    element.Attributes(),
-                    element.Nodes().Select(n => TransformToMetadata(n, data, te)));
-            }
-            return node;
-        }
-
-        private static XElement TransformXmlTextToMetadata(TemplateError te, string xmlText)
-        {
-            XElement xml;
-            try
-            {
-                xml = XElement.Parse(xmlText);
-            }
-            catch (XmlException e)
-            {
-                return CreateParaErrorMessage("XmlException: " + e.Message, te);
-            }
-            string schemaError = ValidatePerSchema(xml);
-            if (schemaError != null)
-                return CreateParaErrorMessage("Schema Validation Error: " + schemaError, te);
-            return xml;
-        }
-
-        private class RunReplacementInfo
-        {
-            public XElement Xml;
-            public string XmlExceptionMessage;
-            public string SchemaValidationMessage;
-        }
-
-        private static string ValidatePerSchema(XElement element)
-        {
-            if (s_PASchemaSets == null)
-            {
-                s_PASchemaSets = new Dictionary<XName, PASchemaSet>()
-                {
-                    {
-                        PA.Content,
-                        new PASchemaSet() {
-                            XsdMarkup =
-                              @"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
-                                  <xs:element name='Content'>
-                                    <xs:complexType>
-                                      <xs:attribute name='Select' type='xs:string' use='required' />
-                                      <xs:attribute name='Optional' type='xs:boolean' use='optional' />
-                                    </xs:complexType>
-                                  </xs:element>
-                                </xs:schema>",
-                        }
-                    },
-                    {
-                        PA.Table,
-                        new PASchemaSet() {
-                            XsdMarkup =
-                              @"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
-                                  <xs:element name='Table'>
-                                    <xs:complexType>
-                                      <xs:attribute name='Select' type='xs:string' use='required' />
-                                    </xs:complexType>
-                                  </xs:element>
-                                </xs:schema>",
-                        }
-                    },
-                    {
-                        PA.Repeat,
-                        new PASchemaSet() {
-                            XsdMarkup =
-                              @"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
-                                  <xs:element name='Repeat'>
-                                    <xs:complexType>
-                                      <xs:attribute name='Select' type='xs:string' use='required' />
-                                      <xs:attribute name='Optional' type='xs:boolean' use='optional' />
-                                    </xs:complexType>
-                                  </xs:element>
-                                </xs:schema>",
-                        }
-                    },
-                    {
-                        PA.EndRepeat,
-                        new PASchemaSet() {
-                            XsdMarkup =
-                              @"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
-                                  <xs:element name='EndRepeat' />
-                                </xs:schema>",
-                        }
-                    },
-                    {
-                        PA.Conditional,
-                        new PASchemaSet() {
-                            XsdMarkup =
-                              @"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
-                                  <xs:element name='Conditional'>
-                                    <xs:complexType>
-                                      <xs:attribute name='Select' type='xs:string' use='required' />
-                                      <xs:attribute name='Match' type='xs:string' use='optional' />
-                                      <xs:attribute name='NotMatch' type='xs:string' use='optional' />
-                                    </xs:complexType>
-                                  </xs:element>
-                                </xs:schema>",
-                        }
-                    },
-                    {
-                        PA.EndConditional,
-                        new PASchemaSet() {
-                            XsdMarkup =
-                              @"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
-                                  <xs:element name='EndConditional' />
-                                </xs:schema>",
-                        }
-                    },
-                };
-                foreach (var item in s_PASchemaSets)
-                {
-                    var itemPAss = item.Value;
-                    XmlSchemaSet schemas = new XmlSchemaSet();
-                    schemas.Add("", XmlReader.Create(new StringReader(itemPAss.XsdMarkup)));
-                    itemPAss.SchemaSet = schemas;
-                }
-            }
-            if (!s_PASchemaSets.ContainsKey(element.Name))
-            {
-                return string.Format("Invalid XML: {0} is not a valid element", element.Name.LocalName);
-            }
-            var paSchemaSet = s_PASchemaSets[element.Name];
-            XDocument d = new XDocument(element);
-            string message = null;
-            d.Validate(paSchemaSet.SchemaSet, (sender, e) =>
-            {
-                if (message == null)
-                    message = e.Message;
-            }, true);
-            if (message != null)
-                return message;
-            return null;
-        }
-
-        private class PA
-        {
-            public static XName Content = "Content";
-            public static XName Table = "Table";
-            public static XName Repeat = "Repeat";
-            public static XName EndRepeat = "EndRepeat";
-            public static XName Conditional = "Conditional";
-            public static XName EndConditional = "EndConditional";
-
-            public static XName Select = "Select";
-            public static XName Optional = "Optional";
-            public static XName Match = "Match";
-            public static XName NotMatch = "NotMatch";
-            public static XName Depth = "Depth";
-        }
-
-        private class PASchemaSet
-        {
-            public string XsdMarkup;
-            public XmlSchemaSet SchemaSet;
-        }
-
-        private static Dictionary<XName, PASchemaSet> s_PASchemaSets = null;
-
-        private class TemplateError
-        {
-            public bool HasError = false;
-        }
-
-        static object ContentReplacementTransform(XNode node, XElement data, TemplateError templateError)
-        {
-            XElement element = node as XElement;
-            if (element != null)
-            {
-                if (element.Name == PA.Content)
-                {
-                    XElement para = element.Descendants(W.p).FirstOrDefault();
-                    XElement run = element.Descendants(W.r).FirstOrDefault();
-
-                    var xPath = (string) element.Attribute(PA.Select);
-                    var optionalString = (string) element.Attribute(PA.Optional);
-                    bool optional = (optionalString != null && optionalString.ToLower() == "true");
-
-                    string newValue;
-                    try
-                    {
-                        newValue = EvaluateXPathToString(data, xPath, optional);
-                    }
-                    catch (XPathException e)
-                    {
-                        return CreateContextErrorMessage(element, "XPathException: " + e.Message, templateError);
-                    }
-
-                    if (para != null)
-                    {
-
-                        XElement p = new XElement(W.p, para.Elements(W.pPr));
-                        foreach(string line in newValue.Split('\n'))
-                        {
-                            p.Add(new XElement(W.r,
-                                    para.Elements(W.r).Elements(W.rPr).FirstOrDefault(),
-                                (p.Elements().Count() > 1) ? new XElement(W.br) : null,
-                                new XElement(W.t, line)));
-                        }
-                        return p;
-                    }
-                    else
-                    {
-                        List<XElement> list = new List<XElement>();
-                        foreach(string line in newValue.Split('\n'))
-                        {
-                            list.Add(new XElement(W.r,
-                                run.Elements().Where(e => e.Name != W.t),
-                                (list.Count > 0) ? new XElement(W.br) : null,
-                                new XElement(W.t, line)));
-                        }
-                        return list;
-                    }
-                }
-                if (element.Name == PA.Repeat)
-                {
-                    string selector = (string)element.Attribute(PA.Select);
-                    var optionalString = (string)element.Attribute(PA.Optional);
-                    bool optional = (optionalString != null && optionalString.ToLower() == "true");
-
-                    IEnumerable<XElement> repeatingData;
-                    try
-                    {
-                        repeatingData = data.XPathSelectElements(selector);
-                    }
-                    catch (XPathException e)
-                    {
-                        return CreateContextErrorMessage(element, "XPathException: " + e.Message, templateError);
-                    }
-                    if (!repeatingData.Any())
-                    {
-                        if (optional)
-                        {
-                            return null;
-                            //XElement para = element.Descendants(W.p).FirstOrDefault();
-                            //if (para != null)
-                            //    return new XElement(W.p, new XElement(W.r));
-                            //else
-                            //    return new XElement(W.r);
-                        }
-                        return CreateContextErrorMessage(element, "Repeat: Select returned no data", templateError);
-                    }
-                    var newContent = repeatingData.Select(d =>
-                        {
-                            var content = element
-                                .Elements()
-                                .Select(e => ContentReplacementTransform(e, d, templateError))
-                                .ToList();
-                            return content;
-                        })
-                        .ToList();
-                    return newContent;
-                }
-                if (element.Name == PA.Table)
-                {
-                    IEnumerable<XElement> tableData;
-                    try
-                    {
-                        tableData = data.XPathSelectElements((string)element.Attribute(PA.Select));
-                    }
-                    catch (XPathException e)
-                    {
-                        return CreateContextErrorMessage(element, "XPathException: " + e.Message, templateError);
-                    }
-                    if (tableData.Count() == 0)
-                        return CreateContextErrorMessage(element, "Table Select returned no data", templateError);
-                    XElement table = element.Element(W.tbl);
-                    XElement protoRow = table.Elements(W.tr).Skip(1).FirstOrDefault();
-                    var footerRowsBeforeTransform = table
-                        .Elements(W.tr)
-                        .Skip(2)
-                        .ToList();
-                    var footerRows = footerRowsBeforeTransform
-                        .Select(x => ContentReplacementTransform(x, data, templateError))
-                        .ToList();
-                    if (protoRow == null)
-                        return CreateContextErrorMessage(element, string.Format("Table does not contain a prototype row"), templateError);
-                    protoRow.Descendants(W.bookmarkStart).Remove();
-                    protoRow.Descendants(W.bookmarkEnd).Remove();
-                    XElement newTable = new XElement(W.tbl,
-                        table.Elements().Where(e => e.Name != W.tr),
-                        table.Elements(W.tr).FirstOrDefault(),
-                        tableData.Select(d =>
-                            new XElement(W.tr,
-                                protoRow.Elements().Where(r => r.Name != W.tc),
-                                protoRow.Elements(W.tc)
-                                    .Select(tc =>
-                                    {
-                                        XElement paragraph = tc.Elements(W.p).FirstOrDefault();
-                                        XElement cellRun = paragraph.Elements(W.r).FirstOrDefault();
-                                        string xPath = paragraph.Value;
-                                        string newValue = null;
-                                        try
-                                        {
-                                            newValue = EvaluateXPathToString(d, xPath, false);
-                                        }
-                                        catch (XPathException e)
-                                        {
-                                            XElement errorCell = new XElement(W.tc,
-                                                tc.Elements().Where(z => z.Name != W.p),
-                                                new XElement(W.p,
-                                                    paragraph.Element(W.pPr),
-                                                    CreateRunErrorMessage(e.Message, templateError)));
-                                            return errorCell;
-                                        }
-
-                                        XElement newCell = new XElement(W.tc,
-                                                   tc.Elements().Where(z => z.Name != W.p),
-                                                   new XElement(W.p,
-                                                       paragraph.Element(W.pPr),
-                                                       new XElement(W.r,
-                                                           cellRun != null ? cellRun.Element(W.rPr) : new XElement(W.rPr),  //if the cell was empty there is no cellrun
-                                                           new XElement(W.t, newValue))));
-                                        return newCell;
-                                    }))),
-                                    footerRows
-                                    );
-                    return newTable;
-                }
-                if (element.Name == PA.Conditional)
-                {
-                    string xPath = (string)element.Attribute(PA.Select);
-                    var match = (string)element.Attribute(PA.Match);
-                    var notMatch = (string)element.Attribute(PA.NotMatch);
-
-                    if (match == null && notMatch == null)
-                        return CreateContextErrorMessage(element, "Conditional: Must specify either Match or NotMatch", templateError);
-                    if (match != null && notMatch != null)
-                        return CreateContextErrorMessage(element, "Conditional: Cannot specify both Match and NotMatch", templateError);
-
-                    string testValue = null; 
-                   
-                    try
-                    {
-                        testValue = EvaluateXPathToString(data, xPath, false);
-                    }
-	                catch (XPathException e)
-                    {
-                        return CreateContextErrorMessage(element, e.Message, templateError);
-                    }
-                  
-                    if ((match != null && testValue == match) || (notMatch != null && testValue != notMatch))
-                    {
-                        var content = element.Elements().Select(e => ContentReplacementTransform(e, data, templateError));
-                        return content;
-                    }
-                    return null;
-                }
-                return new XElement(element.Name,
-                    element.Attributes(),
-                    element.Nodes().Select(n => ContentReplacementTransform(n, data, templateError)));
-            }
-            return node;
-        }
-
-        private static object CreateContextErrorMessage(XElement element, string errorMessage, TemplateError templateError)
-        {
-            XElement para = element.Descendants(W.p).FirstOrDefault();
-            XElement run = element.Descendants(W.r).FirstOrDefault();
-            var errorRun = CreateRunErrorMessage(errorMessage, templateError);
-            if (para != null)
-                return new XElement(W.p, errorRun);
-            else
-                return errorRun;
-        }
-
-        private static XElement CreateRunErrorMessage(string errorMessage, TemplateError templateError)
-        {
-            templateError.HasError = true;
-            var errorRun = new XElement(W.r,
-                new XElement(W.rPr,
-                    new XElement(W.color, new XAttribute(W.val, "FF0000")),
-                    new XElement(W.highlight, new XAttribute(W.val, "yellow"))),
-                    new XElement(W.t, errorMessage));
-            return errorRun;
-        }
-
-        private static XElement CreateParaErrorMessage(string errorMessage, TemplateError templateError)
-        {
-            templateError.HasError = true;
-            var errorPara = new XElement(W.p,
-                new XElement(W.r,
-                    new XElement(W.rPr,
-                        new XElement(W.color, new XAttribute(W.val, "FF0000")),
-                        new XElement(W.highlight, new XAttribute(W.val, "yellow"))),
-                        new XElement(W.t, errorMessage)));
-            return errorPara;
-        }
-
-        private static string EvaluateXPathToString(XElement element, string xPath, bool optional )
-        {
-            object xPathSelectResult;
-            try
-            {
-                //support some cells in the table may not have an xpath expression.
-                if (String.IsNullOrWhiteSpace(xPath)) return String.Empty;
-                
-                xPathSelectResult = element.XPathEvaluate(xPath);
-            }
-            catch (XPathException e)
-            {
-                throw new XPathException("XPathException: " + e.Message, e);
-            }
-
-            if ((xPathSelectResult is IEnumerable) && !(xPathSelectResult is string))
-            {
-                var selectedData = ((IEnumerable) xPathSelectResult).Cast<XObject>();
-                if (!selectedData.Any())
-                {
-                    if (optional) return string.Empty;
-                    throw new XPathException(string.Format("XPath expression ({0}) returned no results", xPath));
-                }
-                if (selectedData.Count() > 1)
-                {
-                    throw new XPathException(string.Format("XPath expression ({0}) returned more than one node", xPath));
-                }
-
-                XObject selectedDatum = selectedData.First(); 
-                
-                if (selectedDatum is XElement) return ((XElement) selectedDatum).Value;
-
-                if (selectedDatum is XAttribute) return ((XAttribute) selectedDatum).Value;
-            }
-
-            return xPathSelectResult.ToString();
-
-        }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 4038
TEAMModelOS.SDK/Module/OpenXmlTool/DocumentBuilder.cs


+ 0 - 833
TEAMModelOS.SDK/Module/OpenXmlTool/ExcelFormula.cs

@@ -1,833 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-/* created on 9/8/2012 9:28:14 AM from peg generator V1.0 using 'ExcelFormula.txt' as input*/
-
-using Peg.Base;
-using System;
-using System.IO;
-using System.Text;
-namespace ExcelFormula
-{
-      
-      enum EExcelFormula{Formula= 1, Expression= 2, InfixTerms= 3, PreAndPostTerm= 4, 
-                          Term= 5, RefInfixTerms= 6, RefTerm= 7, Constant= 8, RefConstant= 9, 
-                          ErrorConstant= 10, LogicalConstant= 11, NumericalConstant= 12, 
-                          SignificandPart= 13, WholeNumberPart= 14, FractionalPart= 15, 
-                          ExponentPart= 16, StringConstant= 17, StringCharacter= 18, HighCharacter= 19, 
-                          ArrayConstant= 20, ConstantListRows= 21, ConstantListRow= 22, 
-                          InfixOperator= 23, ValueInfixOperator= 24, RefInfixOperator= 25, 
-                          UnionOperator= 26, IntersectionOperator= 27, RangeOperator= 28, 
-                          PostfixOperator= 29, PrefixOperator= 30, CellReference= 31, LocalCellReference= 32, 
-                          ExternalCellReference= 33, BookPrefix= 34, BangReference= 35, 
-                          SheetRangeReference= 36, SingleSheetPrefix= 37, SingleSheetReference= 38, 
-                          SingleSheetArea= 39, SingleSheet= 40, SheetRange= 41, WorkbookIndex= 42, 
-                          SheetName= 43, SheetNameCharacter= 44, SheetNameSpecial= 45, 
-                          SheetNameBaseCharacter= 46, A1Reference= 47, A1Cell= 48, A1Area= 49, 
-                          A1Column= 50, A1AbsoluteColumn= 51, A1RelativeColumn= 52, A1Row= 53, 
-                          A1AbsoluteRow= 54, A1RelativeRow= 55, CellFunctionCall= 56, UserDefinedFunctionCall= 57, 
-                          UserDefinedFunctionName= 58, ArgumentList= 59, Argument= 60, 
-                          ArgumentExpression= 61, ArgumentInfixTerms= 62, ArgumentPreAndPostTerm= 63, 
-                          ArgumentTerm= 64, ArgumentRefInfixTerms= 65, ArgumentRefTerm= 66, 
-                          ArgumentInfixOperator= 67, RefArgumentInfixOperator= 68, NameReference= 69, 
-                          ExternalName= 70, BangName= 71, Name= 72, NameStartCharacter= 73, 
-                          NameCharacter= 74, StructureReference= 75, TableIdentifier= 76, 
-                          TableName= 77, IntraTableReference= 78, InnerReference= 79, Keyword= 80, 
-                          KeywordList= 81, ColumnRange= 82, Column= 83, SimpleColumnName= 84, 
-                          EscapeColumnCharacter= 85, UnescapedColumnCharacter= 86, AnyNoSpaceColumnCharacter= 87, 
-                          SpacedComma= 88, SpacedLBracket= 89, SpacedRBracket= 90, ws= 91};
-      class ExcelFormula : PegCharParser 
-      {
-        
-         #region Input Properties
-        public static EncodingClass encodingClass = EncodingClass.ascii;
-        public static UnicodeDetection unicodeDetection = UnicodeDetection.notApplicable;
-        #endregion Input Properties
-        #region Constructors
-        public ExcelFormula()
-            : base()
-        {
-            
-        }
-        public ExcelFormula(string src,TextWriter FerrOut)
-			: base(src,FerrOut)
-        {
-            
-        }
-        #endregion Constructors
-        #region Overrides
-        public override string GetRuleNameFromId(int id)
-        {
-            try
-            {
-                   EExcelFormula ruleEnum = (EExcelFormula)id;
-                    string s= ruleEnum.ToString();
-                    int val;
-                    if( int.TryParse(s,out val) ){
-                        return base.GetRuleNameFromId(id);
-                    }else{
-                        return s;
-                    }
-            }
-            catch (Exception)
-            {
-                return base.GetRuleNameFromId(id);
-            }
-        }
-        public override void GetProperties(out EncodingClass encoding, out UnicodeDetection detection)
-        {
-            encoding = encodingClass;
-            detection = unicodeDetection;
-        } 
-        #endregion Overrides
-		#region Grammar Rules
-        public bool Formula()    /*Formula: Expression (!./FATAL<"end of line expected">);*/
-        {
-
-           return And(()=>  
-                     Expression()
-                  && (    Not(()=> Any() ) || Fatal("end of line expected")) );
-		}
-        public bool Expression()    /*Expression: ws InfixTerms;*/
-        {
-
-           return And(()=>    ws() && InfixTerms() );
-		}
-        public bool InfixTerms()    /*InfixTerms: PreAndPostTerm (InfixOperator ws PreAndPostTerm)*;*/
-        {
-
-           return And(()=>  
-                     PreAndPostTerm()
-                  && OptRepeat(()=>    
-                      And(()=>      
-                               InfixOperator()
-                            && ws()
-                            && PreAndPostTerm() ) ) );
-		}
-        public bool PreAndPostTerm()    /*PreAndPostTerm: (PrefixOperator ws)* Term (PostfixOperator ws)*;*/
-        {
-
-           return And(()=>  
-                     OptRepeat(()=> And(()=>    PrefixOperator() && ws() ) )
-                  && Term()
-                  && OptRepeat(()=> And(()=>    PostfixOperator() && ws() ) ) );
-		}
-        public bool Term()    /*Term: (RefInfixTerms / '(' Expression ')' / Constant) ws;*/
-        {
-
-           return And(()=>  
-                     (    
-                         RefInfixTerms()
-                      || And(()=>    Char('(') && Expression() && Char(')') )
-                      || Constant())
-                  && ws() );
-		}
-        public bool RefInfixTerms()    /*RefInfixTerms: RefTerm (RefInfixOperator ws RefTerm)*;*/
-        {
-
-           return And(()=>  
-                     RefTerm()
-                  && OptRepeat(()=>    
-                      And(()=>    RefInfixOperator() && ws() && RefTerm() ) ) );
-		}
-        public bool RefTerm()    /*RefTerm: '(' ws RefInfixTerms ')' / RefConstant / CellFunctionCall / CellReference / UserDefinedFunctionCall
-	/ NameReference / StructureReference;*/
-        {
-
-           return   
-                     And(()=>    
-                         Char('(')
-                      && ws()
-                      && RefInfixTerms()
-                      && Char(')') )
-                  || RefConstant()
-                  || CellFunctionCall()
-                  || CellReference()
-                  || UserDefinedFunctionCall()
-                  || NameReference()
-                  || StructureReference();
-		}
-        public bool Constant()    /*^^Constant: ErrorConstant / LogicalConstant / NumericalConstant / StringConstant / ArrayConstant;*/
-        {
-
-           return TreeNT((int)EExcelFormula.Constant,()=>
-                  
-                     ErrorConstant()
-                  || LogicalConstant()
-                  || NumericalConstant()
-                  || StringConstant()
-                  || ArrayConstant() );
-		}
-        public bool RefConstant()    /*RefConstant: '#REF!';*/
-        {
-
-           return Char('#','R','E','F','!');
-		}
-        public bool ErrorConstant()    /*ErrorConstant: RefConstant / '#DIV/0!' / '#N/A' / '#NAME?' / '#NULL!' / '#NUM!' / '#VALUE!' / '#GETTING_DATA';*/
-        {
-
-           return   
-                     RefConstant()
-                  || Char('#','D','I','V','/','0','!')
-                  || Char('#','N','/','A')
-                  || Char('#','N','A','M','E','?')
-                  || Char('#','N','U','L','L','!')
-                  || Char('#','N','U','M','!')
-                  || Char('#','V','A','L','U','E','!')
-                  || Char("#GETTING_DATA");
-		}
-        public bool LogicalConstant()    /*LogicalConstant: 'FALSE' / 'TRUE';*/
-        {
-
-           return     Char('F','A','L','S','E') || Char('T','R','U','E');
-		}
-        public bool NumericalConstant()    /*NumericalConstant: '-'? SignificandPart ExponentPart?;*/
-        {
-
-           return And(()=>  
-                     Option(()=> Char('-') )
-                  && SignificandPart()
-                  && Option(()=> ExponentPart() ) );
-		}
-        public bool SignificandPart()    /*SignificandPart: WholeNumberPart FractionalPart? / FractionalPart;*/
-        {
-
-           return   
-                     And(()=>    
-                         WholeNumberPart()
-                      && Option(()=> FractionalPart() ) )
-                  || FractionalPart();
-		}
-        public bool WholeNumberPart()    /*WholeNumberPart: [0-9]+;*/
-        {
-
-           return PlusRepeat(()=> In('0','9') );
-		}
-        public bool FractionalPart()    /*FractionalPart: '.' [0-9]*;*/
-        {
-
-           return And(()=>    Char('.') && OptRepeat(()=> In('0','9') ) );
-		}
-        public bool ExponentPart()    /*ExponentPart: 'E' ('+' / '-')? [0-9]*;*/
-        {
-
-           return And(()=>  
-                     Char('E')
-                  && Option(()=>     Char('+') || Char('-') )
-                  && OptRepeat(()=> In('0','9') ) );
-		}
-        public bool StringConstant()    /*StringConstant: '"' ('""'/StringCharacter)* '"';*/
-        {
-
-           return And(()=>  
-                     Char('"')
-                  && OptRepeat(()=>     Char('"','"') || StringCharacter() )
-                  && Char('"') );
-		}
-        public bool StringCharacter()    /*StringCharacter: [#-~] / '!' / ' ' / HighCharacter;*/
-        {
-
-           return   
-                     In('#','~')
-                  || Char('!')
-                  || Char(' ')
-                  || HighCharacter();
-		}
-        public bool HighCharacter()    /*HighCharacter: [#x80-#xFFFF];*/
-        {
-
-           return In('\u0080','\uffff');
-		}
-        public bool ArrayConstant()    /*^^ArrayConstant: '{' ConstantListRows '}';*/
-        {
-
-           return TreeNT((int)EExcelFormula.ArrayConstant,()=>
-                And(()=>    Char('{') && ConstantListRows() && Char('}') ) );
-		}
-        public bool ConstantListRows()    /*ConstantListRows: ConstantListRow (';' ConstantListRow)*;*/
-        {
-
-           return And(()=>  
-                     ConstantListRow()
-                  && OptRepeat(()=>    
-                      And(()=>    Char(';') && ConstantListRow() ) ) );
-		}
-        public bool ConstantListRow()    /*^^ConstantListRow: Constant (',' Constant)*;*/
-        {
-
-           return TreeNT((int)EExcelFormula.ConstantListRow,()=>
-                And(()=>  
-                     Constant()
-                  && OptRepeat(()=> And(()=>    Char(',') && Constant() ) ) ) );
-		}
-        public bool InfixOperator()    /*InfixOperator: RefInfixOperator / ValueInfixOperator;*/
-        {
-
-           return     RefInfixOperator() || ValueInfixOperator();
-		}
-        public bool ValueInfixOperator()    /*^^ValueInfixOperator: '<>' / '>=' / '<=' / '^' / '*' / '/' / '+' / '-' / '&' / '=' / '<' / '>';*/
-        {
-
-           return TreeNT((int)EExcelFormula.ValueInfixOperator,()=>
-                OneOfLiterals(optimizedLiterals0) );
-		}
-        public bool RefInfixOperator()    /*RefInfixOperator: RangeOperator / UnionOperator / IntersectionOperator;*/
-        {
-
-           return   
-                     RangeOperator()
-                  || UnionOperator()
-                  || IntersectionOperator();
-		}
-        public bool UnionOperator()    /*^^UnionOperator: ',';*/
-        {
-
-           return TreeNT((int)EExcelFormula.UnionOperator,()=>
-                Char(',') );
-		}
-        public bool IntersectionOperator()    /*^^IntersectionOperator: ' ';*/
-        {
-
-           return TreeNT((int)EExcelFormula.IntersectionOperator,()=>
-                Char(' ') );
-		}
-        public bool RangeOperator()    /*^^RangeOperator: ':';*/
-        {
-
-           return TreeNT((int)EExcelFormula.RangeOperator,()=>
-                Char(':') );
-		}
-        public bool PostfixOperator()    /*^^PostfixOperator: '%';*/
-        {
-
-           return TreeNT((int)EExcelFormula.PostfixOperator,()=>
-                Char('%') );
-		}
-        public bool PrefixOperator()    /*^^PrefixOperator: '+' / '-';*/
-        {
-
-           return TreeNT((int)EExcelFormula.PrefixOperator,()=>
-                    Char('+') || Char('-') );
-		}
-        public bool CellReference()    /*CellReference: ExternalCellReference / LocalCellReference;*/
-        {
-
-           return     ExternalCellReference() || LocalCellReference();
-		}
-        public bool LocalCellReference()    /*LocalCellReference: A1Reference;*/
-        {
-
-           return A1Reference();
-		}
-        public bool ExternalCellReference()    /*ExternalCellReference: BangReference / SheetRangeReference / SingleSheetReference;*/
-        {
-
-           return   
-                     BangReference()
-                  || SheetRangeReference()
-                  || SingleSheetReference();
-		}
-        public bool BookPrefix()    /*BookPrefix: WorkbookIndex '!';*/
-        {
-
-           return And(()=>    WorkbookIndex() && Char('!') );
-		}
-        public bool BangReference()    /*BangReference: '!' (A1Reference / '#REF!');*/
-        {
-
-           return And(()=>  
-                     Char('!')
-                  && (    A1Reference() || Char('#','R','E','F','!')) );
-		}
-        public bool SheetRangeReference()    /*SheetRangeReference: SheetRange '!' A1Reference;*/
-        {
-
-           return And(()=>    SheetRange() && Char('!') && A1Reference() );
-		}
-        public bool SingleSheetPrefix()    /*SingleSheetPrefix: SingleSheet '!';*/
-        {
-
-           return And(()=>    SingleSheet() && Char('!') );
-		}
-        public bool SingleSheetReference()    /*SingleSheetReference: SingleSheetPrefix (A1Reference / '#REF!');*/
-        {
-
-           return And(()=>  
-                     SingleSheetPrefix()
-                  && (    A1Reference() || Char('#','R','E','F','!')) );
-		}
-        public bool SingleSheetArea()    /*SingleSheetArea: SingleSheetPrefix A1Area;*/
-        {
-
-           return And(()=>    SingleSheetPrefix() && A1Area() );
-		}
-        public bool SingleSheet()    /*SingleSheet: WorkbookIndex? SheetName / '\'' WorkbookIndex? SheetNameSpecial '\'';*/
-        {
-
-           return   
-                     And(()=>    
-                         Option(()=> WorkbookIndex() )
-                      && SheetName() )
-                  || And(()=>    
-                         Char('\'')
-                      && Option(()=> WorkbookIndex() )
-                      && SheetNameSpecial()
-                      && Char('\'') );
-		}
-        public bool SheetRange()    /*SheetRange: WorkbookIndex? SheetName ':' SheetName / '\'' WorkbookIndex? SheetNameSpecial ':' SheetNameSpecial '\'';*/
-        {
-
-           return   
-                     And(()=>    
-                         Option(()=> WorkbookIndex() )
-                      && SheetName()
-                      && Char(':')
-                      && SheetName() )
-                  || And(()=>    
-                         Char('\'')
-                      && Option(()=> WorkbookIndex() )
-                      && SheetNameSpecial()
-                      && Char(':')
-                      && SheetNameSpecial()
-                      && Char('\'') );
-		}
-        public bool WorkbookIndex()    /*^^WorkbookIndex: '[' WholeNumberPart ']';*/
-        {
-
-           return TreeNT((int)EExcelFormula.WorkbookIndex,()=>
-                And(()=>    Char('[') && WholeNumberPart() && Char(']') ) );
-		}
-        public bool SheetName()    /*^^SheetName: SheetNameCharacter+;*/
-        {
-
-           return TreeNT((int)EExcelFormula.SheetName,()=>
-                PlusRepeat(()=> SheetNameCharacter() ) );
-		}
-        public bool SheetNameCharacter()    /*SheetNameCharacter: [A-Za-z0-9._] / HighCharacter;*/
-        {
-
-           return   
-                     (In('A','Z', 'a','z', '0','9')||OneOf("._"))
-                  || HighCharacter();
-		}
-        public bool SheetNameSpecial()    /*^^SheetNameSpecial: SheetNameBaseCharacter ('\'\''* SheetNameBaseCharacter)*;*/
-        {
-
-           return TreeNT((int)EExcelFormula.SheetNameSpecial,()=>
-                And(()=>  
-                     SheetNameBaseCharacter()
-                  && OptRepeat(()=>    
-                      And(()=>      
-                               OptRepeat(()=> Char('\'','\'') )
-                            && SheetNameBaseCharacter() ) ) ) );
-		}
-        public bool SheetNameBaseCharacter()    /*SheetNameBaseCharacter: [A-Za-z0-9!"#$%&()+,-.;<=>@^_`{|}~ ] / HighCharacter;*/
-        {
-
-           return     OneOf(optimizedCharset0) || HighCharacter();
-		}
-        public bool A1Reference()    /*^^A1Reference: (A1Column ':' A1Column) / (A1Row ':' A1Row) / A1Area / A1Cell;*/
-        {
-
-           return TreeNT((int)EExcelFormula.A1Reference,()=>
-                  
-                     And(()=>    A1Column() && Char(':') && A1Column() )
-                  || And(()=>    A1Row() && Char(':') && A1Row() )
-                  || A1Area()
-                  || A1Cell() );
-		}
-        public bool A1Cell()    /*A1Cell: A1Column A1Row !NameCharacter;*/
-        {
-
-           return And(()=>  
-                     A1Column()
-                  && A1Row()
-                  && Not(()=> NameCharacter() ) );
-		}
-        public bool A1Area()    /*A1Area: A1Cell ':' A1Cell;*/
-        {
-
-           return And(()=>    A1Cell() && Char(':') && A1Cell() );
-		}
-        public bool A1Column()    /*^^A1Column: A1AbsoluteColumn / A1RelativeColumn;*/
-        {
-
-           return TreeNT((int)EExcelFormula.A1Column,()=>
-                    A1AbsoluteColumn() || A1RelativeColumn() );
-		}
-        public bool A1AbsoluteColumn()    /*A1AbsoluteColumn: '$' A1RelativeColumn;*/
-        {
-
-           return And(()=>    Char('$') && A1RelativeColumn() );
-		}
-        public bool A1RelativeColumn()    /*A1RelativeColumn: 'XF' [A-D] / 'X' [A-E] [A-Z] / [A-W][A-Z][A-Z] / [A-Z][A-Z] / [A-Z];*/
-        {
-
-           return   
-                     And(()=>    Char('X','F') && In('A','D') )
-                  || And(()=>    Char('X') && In('A','E') && In('A','Z') )
-                  || And(()=>    In('A','W') && In('A','Z') && In('A','Z') )
-                  || And(()=>    In('A','Z') && In('A','Z') )
-                  || In('A','Z');
-		}
-        public bool A1Row()    /*^^A1Row: A1AbsoluteRow / A1RelativeRow;*/
-        {
-
-           return TreeNT((int)EExcelFormula.A1Row,()=>
-                    A1AbsoluteRow() || A1RelativeRow() );
-		}
-        public bool A1AbsoluteRow()    /*A1AbsoluteRow: '$' A1RelativeRow;*/
-        {
-
-           return And(()=>    Char('$') && A1RelativeRow() );
-		}
-        public bool A1RelativeRow()    /*A1RelativeRow: [1-9][0-9]*;*/
-        {
-
-           return And(()=>    In('1','9') && OptRepeat(()=> In('0','9') ) );
-		}
-        public bool CellFunctionCall()    /*^^CellFunctionCall: A1Cell '(' ArgumentList ')';*/
-        {
-
-           return TreeNT((int)EExcelFormula.CellFunctionCall,()=>
-                And(()=>  
-                     A1Cell()
-                  && Char('(')
-                  && ArgumentList()
-                  && Char(')') ) );
-		}
-        public bool UserDefinedFunctionCall()    /*^^UserDefinedFunctionCall: UserDefinedFunctionName '(' ArgumentList ')';*/
-        {
-
-           return TreeNT((int)EExcelFormula.UserDefinedFunctionCall,()=>
-                And(()=>  
-                     UserDefinedFunctionName()
-                  && Char('(')
-                  && ArgumentList()
-                  && Char(')') ) );
-		}
-        public bool UserDefinedFunctionName()    /*UserDefinedFunctionName: NameReference;*/
-        {
-
-           return NameReference();
-		}
-        public bool ArgumentList()    /*ArgumentList: Argument (',' Argument)*;*/
-        {
-
-           return And(()=>  
-                     Argument()
-                  && OptRepeat(()=> And(()=>    Char(',') && Argument() ) ) );
-		}
-        public bool Argument()    /*Argument: ArgumentExpression / ws;*/
-        {
-
-           return     ArgumentExpression() || ws();
-		}
-        public bool ArgumentExpression()    /*^^ArgumentExpression: ws ArgumentInfixTerms;*/
-        {
-
-           return TreeNT((int)EExcelFormula.ArgumentExpression,()=>
-                And(()=>    ws() && ArgumentInfixTerms() ) );
-		}
-        public bool ArgumentInfixTerms()    /*ArgumentInfixTerms: ArgumentPreAndPostTerm (ArgumentInfixOperator ws ArgumentPreAndPostTerm)*;*/
-        {
-
-           return And(()=>  
-                     ArgumentPreAndPostTerm()
-                  && OptRepeat(()=>    
-                      And(()=>      
-                               ArgumentInfixOperator()
-                            && ws()
-                            && ArgumentPreAndPostTerm() ) ) );
-		}
-        public bool ArgumentPreAndPostTerm()    /*ArgumentPreAndPostTerm: (PrefixOperator ws)* ArgumentTerm (PostfixOperator ws)*;*/
-        {
-
-           return And(()=>  
-                     OptRepeat(()=> And(()=>    PrefixOperator() && ws() ) )
-                  && ArgumentTerm()
-                  && OptRepeat(()=> And(()=>    PostfixOperator() && ws() ) ) );
-		}
-        public bool ArgumentTerm()    /*ArgumentTerm: (ArgumentRefInfixTerms / '(' Expression ')' / Constant) ws;*/
-        {
-
-           return And(()=>  
-                     (    
-                         ArgumentRefInfixTerms()
-                      || And(()=>    Char('(') && Expression() && Char(')') )
-                      || Constant())
-                  && ws() );
-		}
-        public bool ArgumentRefInfixTerms()    /*ArgumentRefInfixTerms: ArgumentRefTerm (RefArgumentInfixOperator ws ArgumentRefTerm)*;*/
-        {
-
-           return And(()=>  
-                     ArgumentRefTerm()
-                  && OptRepeat(()=>    
-                      And(()=>      
-                               RefArgumentInfixOperator()
-                            && ws()
-                            && ArgumentRefTerm() ) ) );
-		}
-        public bool ArgumentRefTerm()    /*ArgumentRefTerm: '(' ws RefInfixTerms ')' / RefConstant / CellFunctionCall / CellReference / UserDefinedFunctionCall
-	/ NameReference / StructureReference;*/
-        {
-
-           return   
-                     And(()=>    
-                         Char('(')
-                      && ws()
-                      && RefInfixTerms()
-                      && Char(')') )
-                  || RefConstant()
-                  || CellFunctionCall()
-                  || CellReference()
-                  || UserDefinedFunctionCall()
-                  || NameReference()
-                  || StructureReference();
-		}
-        public bool ArgumentInfixOperator()    /*ArgumentInfixOperator: RefArgumentInfixOperator / ValueInfixOperator;*/
-        {
-
-           return     RefArgumentInfixOperator() || ValueInfixOperator();
-		}
-        public bool RefArgumentInfixOperator()    /*RefArgumentInfixOperator: RangeOperator / IntersectionOperator;*/
-        {
-
-           return     RangeOperator() || IntersectionOperator();
-		}
-        public bool NameReference()    /*^^NameReference: (ExternalName / Name) !'[';*/
-        {
-
-           return TreeNT((int)EExcelFormula.NameReference,()=>
-                And(()=>  
-                     (    ExternalName() || Name())
-                  && Not(()=> Char('[') ) ) );
-		}
-        public bool ExternalName()    /*ExternalName: BangName / (SingleSheetPrefix / BookPrefix) Name;*/
-        {
-
-           return   
-                     BangName()
-                  || And(()=>    
-                         (    SingleSheetPrefix() || BookPrefix())
-                      && Name() );
-		}
-        public bool BangName()    /*BangName: '!' Name;*/
-        {
-
-           return And(()=>    Char('!') && Name() );
-		}
-        public bool Name()    /*Name: NameStartCharacter NameCharacter*;*/
-        {
-
-           return And(()=>  
-                     NameStartCharacter()
-                  && OptRepeat(()=> NameCharacter() ) );
-		}
-        public bool NameStartCharacter()    /*NameStartCharacter: [_\\A-Za-z] / HighCharacter;*/
-        {
-
-           return   
-                     (In('A','Z', 'a','z')||OneOf("_\\"))
-                  || HighCharacter();
-		}
-        public bool NameCharacter()    /*NameCharacter: NameStartCharacter / [0-9] / '.' / '?' / HighCharacter;*/
-        {
-
-           return   
-                     NameStartCharacter()
-                  || In('0','9')
-                  || Char('.')
-                  || Char('?')
-                  || HighCharacter();
-		}
-        public bool StructureReference()    /*^^StructureReference: TableIdentifier? IntraTableReference;*/
-        {
-
-           return TreeNT((int)EExcelFormula.StructureReference,()=>
-                And(()=>  
-                     Option(()=> TableIdentifier() )
-                  && IntraTableReference() ) );
-		}
-        public bool TableIdentifier()    /*TableIdentifier: BookPrefix? TableName;*/
-        {
-
-           return And(()=>    Option(()=> BookPrefix() ) && TableName() );
-		}
-        public bool TableName()    /*TableName: Name;*/
-        {
-
-           return Name();
-		}
-        public bool IntraTableReference()    /*IntraTableReference: SpacedLBracket InnerReference SpacedRBracket / Keyword / '[' SimpleColumnName ']';*/
-        {
-
-           return   
-                     And(()=>    
-                         SpacedLBracket()
-                      && InnerReference()
-                      && SpacedRBracket() )
-                  || Keyword()
-                  || And(()=>    
-                         Char('[')
-                      && SimpleColumnName()
-                      && Char(']') );
-		}
-        public bool InnerReference()    /*InnerReference: (KeywordList SpacedComma)? ColumnRange / KeywordList;*/
-        {
-
-           return   
-                     And(()=>    
-                         Option(()=>      
-                            And(()=>    KeywordList() && SpacedComma() ) )
-                      && ColumnRange() )
-                  || KeywordList();
-		}
-        public bool Keyword()    /*Keyword: '[#All]' / '[#Data]' / '[#Headers]' / '[#Totals]' / '[#This Row]';*/
-        {
-
-           return   
-                     Char('[','#','A','l','l',']')
-                  || Char('[','#','D','a','t','a',']')
-                  || Char("[#Headers]")
-                  || Char("[#Totals]")
-                  || Char("[#This Row]");
-		}
-        public bool KeywordList()    /*KeywordList: '[#Headers]' SpacedComma '[#Data]' / '[#Data]' SpacedComma '[#Totals]' / Keyword;*/
-        {
-
-           return   
-                     And(()=>    
-                         Char("[#Headers]")
-                      && SpacedComma()
-                      && Char('[','#','D','a','t','a',']') )
-                  || And(()=>    
-                         Char('[','#','D','a','t','a',']')
-                      && SpacedComma()
-                      && Char("[#Totals]") )
-                  || Keyword();
-		}
-        public bool ColumnRange()    /*ColumnRange: Column (':' Column)?;*/
-        {
-
-           return And(()=>  
-                     Column()
-                  && Option(()=> And(()=>    Char(':') && Column() ) ) );
-		}
-        public bool Column()    /*Column: '[' ws SimpleColumnName ws ']' / SimpleColumnName;*/
-        {
-
-           return   
-                     And(()=>    
-                         Char('[')
-                      && ws()
-                      && SimpleColumnName()
-                      && ws()
-                      && Char(']') )
-                  || SimpleColumnName();
-		}
-        public bool SimpleColumnName()    /*SimpleColumnName: AnyNoSpaceColumnCharacter+ (ws AnyNoSpaceColumnCharacter+)*;*/
-        {
-
-           return And(()=>  
-                     PlusRepeat(()=> AnyNoSpaceColumnCharacter() )
-                  && OptRepeat(()=>    
-                      And(()=>      
-                               ws()
-                            && PlusRepeat(()=> AnyNoSpaceColumnCharacter() ) ) ) );
-		}
-        public bool EscapeColumnCharacter()    /*EscapeColumnCharacter: '\'' / '#' / '[' / ']';*/
-        {
-
-           return     Char('\'') || Char('#') || Char('[') || Char(']');
-		}
-        public bool UnescapedColumnCharacter()    /*UnescapedColumnCharacter: [A-Za-z0-9!"#$%&()*+,-./:;<=>?@\\^_`{|}~] / HighCharacter;*/
-        {
-
-           return     OneOf(optimizedCharset1) || HighCharacter();
-		}
-        public bool AnyNoSpaceColumnCharacter()    /*AnyNoSpaceColumnCharacter: ('\'' EscapeColumnCharacter) / UnescapedColumnCharacter;*/
-        {
-
-           return   
-                     And(()=>    Char('\'') && EscapeColumnCharacter() )
-                  || UnescapedColumnCharacter();
-		}
-        public bool SpacedComma()    /*SpacedComma: ' '? ',' ' '?;*/
-        {
-
-           return And(()=>  
-                     Option(()=> Char(' ') )
-                  && Char(',')
-                  && Option(()=> Char(' ') ) );
-		}
-        public bool SpacedLBracket()    /*SpacedLBracket: '[' ' '?;*/
-        {
-
-           return And(()=>    Char('[') && Option(()=> Char(' ') ) );
-		}
-        public bool SpacedRBracket()    /*SpacedRBracket: ' '? ']';*/
-        {
-
-           return And(()=>    Option(()=> Char(' ') ) && Char(']') );
-		}
-        public bool ws()    /*ws: ' '*;*/
-        {
-
-           return OptRepeat(()=> Char(' ') );
-		}
-		#endregion Grammar Rules
-
-        #region Optimization Data 
-        internal static OptimizedCharset optimizedCharset0;
-        internal static OptimizedCharset optimizedCharset1;
-        
-        internal static OptimizedLiterals optimizedLiterals0;
-        
-        static ExcelFormula()
-        {
-            {
-               OptimizedCharset.Range[] ranges = new OptimizedCharset.Range[]
-                  {new OptimizedCharset.Range('A','Z'),
-                   new OptimizedCharset.Range('a','z'),
-                   new OptimizedCharset.Range('0','9'),
-                   new OptimizedCharset.Range(',','.'),
-                   };
-               char[] oneOfChars = new char[]    {'!','"','#','$','%'
-                                                  ,'&','(',')','+',';'
-                                                  ,'<','=','>','@','^'
-                                                  ,'_','`','{','|','}'
-                                                  ,'~',' '};
-               optimizedCharset0= new OptimizedCharset(ranges,oneOfChars);
-            }
-            
-            {
-               OptimizedCharset.Range[] ranges = new OptimizedCharset.Range[]
-                  {new OptimizedCharset.Range('A','Z'),
-                   new OptimizedCharset.Range('a','z'),
-                   new OptimizedCharset.Range('0','9'),
-                   new OptimizedCharset.Range(',','.'),
-                   };
-               char[] oneOfChars = new char[]    {'!','"','#','$','%'
-                                                  ,'&','(',')','*','+'
-                                                  ,'/',':',';','<','='
-                                                  ,'>','?','@','\\','^'
-                                                  ,'_','`','{','|','}'
-                                                  ,'~'};
-               optimizedCharset1= new OptimizedCharset(ranges,oneOfChars);
-            }
-            
-            
-            {
-               string[] literals=
-               { "<>",">=","<=","^","*","/","+","-",
-                  "&","=","<",">" };
-               optimizedLiterals0= new OptimizedLiterals(literals);
-            }
-
-            
-        }
-        #endregion Optimization Data 
-           }
-}

+ 0 - 416
TEAMModelOS.SDK/Module/OpenXmlTool/FieldRetriever.cs

@@ -1,416 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public class FieldRetriever
-    {
-        public static string InstrText(XElement root, int id)
-        {
-
-            XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
-
-#if false
-            // This is the old code.  Both versions work - the caching version is significantly faster.
-            var relevantElements = root.Descendants()
-                .Where(e =>
-                {
-                    Stack<FieldElementTypeInfo> s = e.Annotation<Stack<FieldElementTypeInfo>>();
-                    if (s != null)
-                        return s.Any(z => z.Id == id &&
-                            z.FieldElementType == FieldElementTypeEnum.InstrText);
-                    return false;
-                })
-                .ToList();
-#else
-            var cachedAnnotationInformation = root.Annotation<Dictionary<int, List<XElement>>>();
-            if (cachedAnnotationInformation == null)
-                throw new OpenXmlPowerToolsException("Internal error");
-
-            // it is possible that a field code contains no instr text
-            if (!cachedAnnotationInformation.ContainsKey(id))
-                return "";
-            var relevantElements = cachedAnnotationInformation[id];
-#endif
-
-            var groupedSubFields = relevantElements
-                .GroupAdjacent(e =>
-                {
-                    Stack<FieldElementTypeInfo> s = e.Annotation<Stack<FieldElementTypeInfo>>();
-                    var stackElement = s.FirstOrDefault(z => z.Id == id);
-                    var elementsBefore = s.TakeWhile(z => z != stackElement);
-                    return elementsBefore.Any();
-                })
-                .ToList();
-
-            var instrText = groupedSubFields
-                .Select(g =>
-                {
-                    if (g.Key == false)
-                    {
-                        return g.Select(e =>
-                        {
-                            Stack<FieldElementTypeInfo> s = e.Annotation<Stack<FieldElementTypeInfo>>();
-                            var stackElement = s.FirstOrDefault(z => z.Id == id);
-                            if (stackElement.FieldElementType == FieldElementTypeEnum.InstrText &&
-                                e.Name == w + "instrText")
-                                return e.Value;
-                            return "";
-                        })
-                            .StringConcatenate();
-                    }
-                    else
-                    {
-                        Stack<FieldElementTypeInfo> s = g.First().Annotation<Stack<FieldElementTypeInfo>>();
-                        var stackElement = s.FirstOrDefault(z => z.Id == id);
-                        var elementBefore = s.TakeWhile(z => z != stackElement).Last();
-                        var subFieldId = elementBefore.Id;
-                        return InstrText(root, subFieldId);
-                    }
-                })
-                .StringConcatenate();
-
-            return "{" + instrText + "}";
-        }
-
-        public static void AnnotateWithFieldInfo(OpenXmlPart part)
-        {
-            XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
-
-            XElement root = part.GetXDocument().Root;
-            var r = root.DescendantsAndSelf()
-                .Rollup(
-                    new FieldElementTypeStack
-                    {
-                        Id = 0,
-                        FiStack = null,
-                    },
-                    (e, s) =>
-                    {
-                        if (e.Name == w + "fldChar")
-                        {
-                            if (e.Attribute(w + "fldCharType").Value == "begin")
-                            {
-                                Stack<FieldElementTypeInfo> fis;
-                                if (s.FiStack == null)
-                                    fis = new Stack<FieldElementTypeInfo>();
-                                else
-                                    fis = new Stack<FieldElementTypeInfo>(s.FiStack.Reverse());
-                                fis.Push(
-                                    new FieldElementTypeInfo
-                                    {
-                                        Id = s.Id + 1,
-                                        FieldElementType = FieldElementTypeEnum.Begin,
-                                    });
-                                return new FieldElementTypeStack
-                                {
-                                    Id = s.Id + 1,
-                                    FiStack = fis,
-                                };
-                            };
-                            if (e.Attribute(w + "fldCharType").Value == "separate")
-                            {
-                                Stack<FieldElementTypeInfo> fis = new Stack<FieldElementTypeInfo>(s.FiStack.Reverse());
-                                FieldElementTypeInfo wfi = fis.Pop();
-                                fis.Push(
-                                    new FieldElementTypeInfo
-                                    {
-                                        Id = wfi.Id,
-                                        FieldElementType = FieldElementTypeEnum.Separate,
-                                    });
-                                return new FieldElementTypeStack
-                                {
-                                    Id = s.Id,
-                                    FiStack = fis,
-                                };
-                            }
-                            if (e.Attribute(w + "fldCharType").Value == "end")
-                            {
-                                Stack<FieldElementTypeInfo> fis = new Stack<FieldElementTypeInfo>(s.FiStack.Reverse());
-                                FieldElementTypeInfo wfi = fis.Pop();
-                                return new FieldElementTypeStack
-                                {
-                                    Id = s.Id,
-                                    FiStack = fis,
-                                };
-                            }
-                        }
-                        if (s.FiStack == null || s.FiStack.Count() == 0)
-                            return s;
-                        FieldElementTypeInfo wfi3 = s.FiStack.Peek();
-                        if (wfi3.FieldElementType == FieldElementTypeEnum.Begin)
-                        {
-                            Stack<FieldElementTypeInfo> fis = new Stack<FieldElementTypeInfo>(s.FiStack.Reverse());
-                            FieldElementTypeInfo wfi2 = fis.Pop();
-                            fis.Push(
-                                new FieldElementTypeInfo
-                                {
-                                    Id = wfi2.Id,
-                                    FieldElementType = FieldElementTypeEnum.InstrText,
-                                });
-                            return new FieldElementTypeStack
-                            {
-                                Id = s.Id,
-                                FiStack = fis,
-                            };
-                        }
-                        if (wfi3.FieldElementType == FieldElementTypeEnum.Separate)
-                        {
-                            Stack<FieldElementTypeInfo> fis = new Stack<FieldElementTypeInfo>(s.FiStack.Reverse());
-                            FieldElementTypeInfo wfi2 = fis.Pop();
-                            fis.Push(
-                                new FieldElementTypeInfo
-                                {
-                                    Id = wfi2.Id,
-                                    FieldElementType = FieldElementTypeEnum.Result,
-                                });
-                            return new FieldElementTypeStack
-                            {
-                                Id = s.Id,
-                                FiStack = fis,
-                            };
-                        }
-                        if (wfi3.FieldElementType == FieldElementTypeEnum.End)
-                        {
-                            Stack<FieldElementTypeInfo> fis = new Stack<FieldElementTypeInfo>(s.FiStack.Reverse());
-                            fis.Pop();
-                            if (!fis.Any())
-                                fis = null;
-                            return new FieldElementTypeStack
-                            {
-                                Id = s.Id,
-                                FiStack = fis,
-                            };
-                        }
-                        return s;
-                    });
-            var elementPlusInfo = root.DescendantsAndSelf().PtZip(r, (t1, t2) =>
-            {
-                return new
-                {
-                    Element = t1,
-                    Id = t2.Id,
-                    WmlFieldInfoStack = t2.FiStack,
-                };
-            });
-            foreach (var item in elementPlusInfo)
-            {
-                if (item.WmlFieldInfoStack != null)
-                    item.Element.AddAnnotation(item.WmlFieldInfoStack);
-            }
-
-            //This code is useful when you want to take a look at the annotations, making sure that they are made correctly.
-            //
-            //foreach (var desc in root.DescendantsAndSelf())
-            //{
-            //    Stack<FieldElementTypeInfo> s = desc.Annotation<Stack<FieldElementTypeInfo>>();
-            //    if (s != null)
-            //    {
-            //        Console.WriteLine(desc.Name.LocalName.PadRight(20));
-            //        foreach (var item in s)
-            //        {
-            //            Console.WriteLine("    {0:0000} {1}", item.Id, item.FieldElementType.ToString());
-            //            Console.ReadKey();
-            //        }
-            //    }
-            //}
-
-            var cachedAnnotationInformation = new Dictionary<int, List<XElement>>();
-            foreach (var desc in root.DescendantsTrimmed(d => d.Name == W.rPr || d.Name == W.pPr))
-            {
-                Stack<FieldElementTypeInfo> s = desc.Annotation<Stack<FieldElementTypeInfo>>();
-
-                if (s != null )
-                {
-                    foreach (var item in s)
-                    {
-                        if (item.FieldElementType == FieldElementTypeEnum.InstrText)
-                        {
-                            if (cachedAnnotationInformation.ContainsKey(item.Id))
-                            {
-                                cachedAnnotationInformation[item.Id].Add(desc);
-                            }
-                            else
-                            {
-                                cachedAnnotationInformation.Add(item.Id, new List<XElement>() { desc });
-                            }
-                        }
-                    }
-                }
-            }
-            root.AddAnnotation(cachedAnnotationInformation);
-        }
-
-        private enum State
-        {
-            InToken,
-            InWhiteSpace,
-            InQuotedToken,
-            OnOpeningQuote,
-            OnClosingQuote,
-            OnBackslash,
-        }
-
-        private static string[] GetTokens(string field)
-        {
-            State state = State.InWhiteSpace;
-            int tokenStart = 0;
-            char quoteStart = char.MinValue;
-            List<string> tokens = new List<string>();
-            for (int c = 0; c < field.Length; c++)
-            {
-                if (Char.IsWhiteSpace(field[c]))
-                {
-                    if (state == State.InToken)
-                    {
-                        tokens.Add(field.Substring(tokenStart, c - tokenStart));
-                        state = State.InWhiteSpace;
-                        continue;
-                    }
-                    if (state == State.OnOpeningQuote)
-                    {
-                        tokenStart = c;
-                        state = State.InQuotedToken;
-                    }
-                    if (state == State.OnClosingQuote)
-                        state = State.InWhiteSpace;
-                    continue;
-                }
-                if (field[c] == '\\')
-                {
-                    if (state == State.InQuotedToken)
-                    {
-                        state = State.OnBackslash;
-                        continue;
-                    }
-                }
-                if (state == State.OnBackslash)
-                {
-                    state = State.InQuotedToken;
-                    continue;
-                }
-                if (field[c] == '"' || field[c] == '\'' || field[c] == 0x201d)
-                {
-                    if (state == State.InWhiteSpace)
-                    {
-                        quoteStart = field[c];
-                        state = State.OnOpeningQuote;
-                        continue;
-                    }
-                    if (state == State.InQuotedToken)
-                    {
-                        if (field[c] == quoteStart)
-                        {
-                            tokens.Add(field.Substring(tokenStart, c - tokenStart));
-                            state = State.OnClosingQuote;
-                            continue;
-                        }
-                        continue;
-                    }
-                    if (state == State.OnOpeningQuote)
-                    {
-                        if (field[c] == quoteStart)
-                        {
-                            state = State.OnClosingQuote;
-                            continue;
-                        }
-                        else
-                        {
-                            tokenStart = c;
-                            state = State.InQuotedToken;
-                            continue;
-                        }
-                    }
-                    continue;
-                }
-                if (state == State.InWhiteSpace)
-                {
-                    tokenStart = c;
-                    state = State.InToken;
-                    continue;
-                }
-                if (state == State.OnOpeningQuote)
-                {
-                    tokenStart = c;
-                    state = State.InQuotedToken;
-                    continue;
-                }
-                if (state == State.OnClosingQuote)
-                {
-                    tokenStart = c;
-                    state = State.InToken;
-                    continue;
-                }
-            }
-            if (state == State.InToken)
-                tokens.Add(field.Substring(tokenStart, field.Length - tokenStart));
-            return tokens.ToArray();
-        }
-
-        public static FieldInfo ParseField(string field)
-        {
-            FieldInfo emptyField = new FieldInfo
-            {
-                FieldType = "",
-                Arguments = new string[] { },
-                Switches = new string[] { },
-            };
-
-            if (field.Length == 0)
-                return emptyField;
-            string fieldType = field.TrimStart().Split(' ').FirstOrDefault();
-            if (fieldType == null)
-                return emptyField;
-            if (fieldType.ToUpper() != "HYPERLINK" &&
-                fieldType.ToUpper() != "REF" &&
-                fieldType.ToUpper() != "SEQ" &&
-                fieldType.ToUpper() != "STYLEREF")
-                return emptyField;
-            string[] tokens = GetTokens(field);
-            if (tokens.Length == 0)
-                return emptyField;
-            FieldInfo fieldInfo = new FieldInfo()
-            {
-                FieldType = tokens[0],
-                Switches = tokens.Where(t => t[0] == '\\').ToArray(),
-                Arguments = tokens.Skip(1).Where(t => t[0] != '\\').ToArray(),
-            };
-            return fieldInfo;
-        }
-
-        public class FieldInfo
-        {
-            public string FieldType;
-            public string[] Switches;
-            public string[] Arguments;
-        }
-
-        public enum FieldElementTypeEnum
-        {
-            Begin,
-            InstrText,
-            Separate,
-            Result,
-            End,
-        };
-
-        public class FieldElementTypeInfo
-        {
-            public int Id;
-            public FieldElementTypeEnum FieldElementType;
-        }
-
-        public class FieldElementTypeStack
-        {
-            public int Id;
-            public Stack<FieldElementTypeInfo> FiStack;
-        }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 3510
TEAMModelOS.SDK/Module/OpenXmlTool/FormattingAssembler.cs


+ 0 - 240
TEAMModelOS.SDK/Module/OpenXmlTool/GetListItemText_Default.cs

@@ -1,240 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text;
-
-namespace OpenXmlPowerTools
-{
-    class ListItemTextGetter_Default
-    {
-        private static string[] RomanOnes =
-        {
-            "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"
-        };
-
-        private static string[] RomanTens =
-        {
-            "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"
-        };
-
-        private static string[] RomanHundreds =
-        {
-            "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "M"
-        };
-
-        private static string[] RomanThousands =
-        {
-            "", "M", "MM", "MMM", "MMMM", "MMMMM", "MMMMMM", "MMMMMMM", "MMMMMMMM",
-            "MMMMMMMMM", "MMMMMMMMMM"
-        };
-
-        private static string[] OneThroughNineteen = {
-            "one", "two", "three", "four", "five", "six", "seven", "eight",
-            "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
-            "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
-        };
-
-        private static string[] Tens = {
-            "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
-            "eighty", "ninety"
-        };
-
-        private static string[] OrdinalOneThroughNineteen = {
-            "first", "second", "third", "fourth", "fifth", "sixth",
-            "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth",
-            "thirteenth", "fourteenth", "fifteenth", "sixteenth",
-            "seventeenth", "eighteenth", "nineteenth"
-        };
-
-        private static string[] OrdinalTenths = {
-            "tenth", "twentieth", "thirtieth", "fortieth", "fiftieth",
-            "sixtieth", "seventieth", "eightieth", "ninetieth"
-        };
-
-        public static string GetListItemText(string languageCultureName, int levelNumber, string numFmt)
-        {
-            if (numFmt == "none")
-            {
-                return "";
-            }
-            if (numFmt == "decimal")
-            {
-                return levelNumber.ToString();
-            }
-            if (numFmt == "decimalZero")
-            {
-                if (levelNumber <= 9)
-                    return "0" + levelNumber.ToString();
-                else
-                    return levelNumber.ToString();
-            }
-            if (numFmt == "upperRoman")
-            {
-                int ones = levelNumber % 10;
-                int tens = (levelNumber % 100) / 10;
-                int hundreds = (levelNumber % 1000) / 100;
-                int thousands = levelNumber / 1000;
-                return RomanThousands[thousands] + RomanHundreds[hundreds] +
-                    RomanTens[tens] + RomanOnes[ones];
-            }
-            if (numFmt == "lowerRoman")
-            {
-                int ones = levelNumber % 10;
-                int tens = (levelNumber % 100) / 10;
-                int hundreds = (levelNumber % 1000) / 100;
-                int thousands = levelNumber / 1000;
-                return (RomanThousands[thousands] + RomanHundreds[hundreds] +
-                    RomanTens[tens] + RomanOnes[ones]).ToLower();
-            }
-            if (numFmt == "upperLetter")
-            {
-                int levelNumber2 = levelNumber % 780;
-                if (levelNumber2 == 0)
-                    levelNumber2 = 780;
-                string a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-                int c = (levelNumber2 - 1) / 26;
-                int n = (levelNumber2 - 1) % 26;
-                char x = a[n];
-                return "".PadRight(c + 1, x);
-            }
-            if (numFmt == "lowerLetter")
-            {
-                int levelNumber3 = levelNumber % 780;
-                if (levelNumber3 == 0)
-                    levelNumber3 = 780;
-                string a = "abcdefghijklmnopqrstuvwxyz";
-                int c = (levelNumber3 - 1) / 26;
-                int n = (levelNumber3 - 1) % 26;
-                char x = a[n];
-                return "".PadRight(c + 1, x);
-            }
-            if (numFmt == "ordinal")
-            {
-                string suffix;
-                if (levelNumber % 100 == 11 || levelNumber % 100 == 12 ||
-                    levelNumber % 100 == 13)
-                    suffix = "th";
-                else if (levelNumber % 10 == 1)
-                    suffix = "st";
-                else if (levelNumber % 10 == 2)
-                    suffix = "nd";
-                else if (levelNumber % 10 == 3)
-                    suffix = "rd";
-                else
-                    suffix = "th";
-                return levelNumber.ToString() + suffix;
-            }
-            if (numFmt == "cardinalText")
-            {
-                string result = "";
-                int t1 = levelNumber / 1000;
-                int t2 = levelNumber % 1000;
-                if (t1 >= 1)
-                    result += OneThroughNineteen[t1 - 1] + " thousand";
-                if (t1 >= 1 && t2 == 0)
-                    return result.Substring(0, 1).ToUpper() +
-                        result.Substring(1);
-                if (t1 >= 1)
-                    result += " ";
-                int h1 = (levelNumber % 1000) / 100;
-                int h2 = levelNumber % 100;
-                if (h1 >= 1)
-                    result += OneThroughNineteen[h1 - 1] + " hundred";
-                if (h1 >= 1 && h2 == 0)
-                    return result.Substring(0, 1).ToUpper() +
-                        result.Substring(1);
-                if (h1 >= 1)
-                    result += " ";
-                int z = levelNumber % 100;
-                if (z <= 19)
-                    result += OneThroughNineteen[z - 1];
-                else
-                {
-                    int x = z / 10;
-                    int r = z % 10;
-                    result += Tens[x - 1];
-                    if (r >= 1)
-                        result += "-" + OneThroughNineteen[r - 1];
-                }
-                return result.Substring(0, 1).ToUpper() +
-                    result.Substring(1);
-            }
-            if (numFmt == "ordinalText")
-            {
-                string result = "";
-                int t1 = levelNumber / 1000;
-                int t2 = levelNumber % 1000;
-                if (t1 >= 1 && t2 != 0)
-                    result += OneThroughNineteen[t1 - 1] + " thousand";
-                if (t1 >= 1 && t2 == 0)
-                {
-                    result += OneThroughNineteen[t1 - 1] + " thousandth";
-                    return result.Substring(0, 1).ToUpper() +
-                        result.Substring(1);
-                }
-                if (t1 >= 1)
-                    result += " ";
-                int h1 = (levelNumber % 1000) / 100;
-                int h2 = levelNumber % 100;
-                if (h1 >= 1 && h2 != 0)
-                    result += OneThroughNineteen[h1 - 1] + " hundred";
-                if (h1 >= 1 && h2 == 0)
-                {
-                    result += OneThroughNineteen[h1 - 1] + " hundredth";
-                    return result.Substring(0, 1).ToUpper() +
-                        result.Substring(1);
-                }
-                if (h1 >= 1)
-                    result += " ";
-                int z = levelNumber % 100;
-                if (z <= 19)
-                    result += OrdinalOneThroughNineteen[z - 1];
-                else
-                {
-                    int x = z / 10;
-                    int r = z % 10;
-                    if (r == 0)
-                        result += OrdinalTenths[x - 1];
-                    else
-                        result += Tens[x - 1];
-                    if (r >= 1)
-                        result += "-" + OrdinalOneThroughNineteen[r - 1];
-                }
-                return result.Substring(0, 1).ToUpper() +
-                    result.Substring(1);
-            }
-            if (numFmt == "01, 02, 03, ...")
-            {
-                return string.Format("{0:00}", levelNumber);
-            }
-            if (numFmt == "001, 002, 003, ...")
-            {
-                return string.Format("{0:000}", levelNumber);
-            }
-            if (numFmt == "0001, 0002, 0003, ...")
-            {
-                return string.Format("{0:0000}", levelNumber);
-            }
-            if (numFmt == "00001, 00002, 00003, ...")
-            {
-                return string.Format("{0:00000}", levelNumber);
-            }
-            if (numFmt == "bullet")
-                return "";
-            if (numFmt == "decimalEnclosedCircle")
-            {
-                if (levelNumber >= 1 && levelNumber <= 20)
-                {
-                    // 9311 + levelNumber
-                    var s = new string(new[] { (char)(9311 + levelNumber) });
-                    return s;
-                }
-                return levelNumber.ToString();
-            }
-            return levelNumber.ToString();
-        }
-    }
-}

+ 0 - 233
TEAMModelOS.SDK/Module/OpenXmlTool/GetListItemText_fr_FR.cs

@@ -1,233 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text;
-
-namespace OpenXmlPowerTools
-{
-    public class ListItemTextGetter_fr_FR
-    {
-        private static string[] OneThroughNineteen = {
-            "", "un", "deux", "trois", "quatre", "cinq", "six", "sept", "huit",
-            "neuf", "dix", "onze", "douze", "treize", "quatorze",
-            "quinze", "seize", "dix-sept", "dix-huit", "dix-neuf"
-        };
-
-        private static string[] Tens = {
-            "", "dix", "vingt", "trente", "quarante", "cinquante", "soixante", "soixante-dix",
-            "quatre-vingt", "quatre-vingt-dix"
-        };
-
-        private static string[] OrdinalOneThroughNineteen = {
-            "", "unième", "deuxième", "troisième", "quatrième", "cinquième", "sixième",
-            "septième", "huitième", "neuvième", "dixième", "onzième", "douzième",
-            "treizième", "quatorzième", "quinzième", "seizième",
-            "dix-septième", "dix-huitième", "dix-neuvième"
-        };
-
-        private static string[] OrdinalTenths = {
-            "", "dixième", "vingtième", "trentième", "quarantième", "cinquantième",
-            "soixantième", "soixante-dixième", "quatre-vingtième", "quatre-vingt-dixième"
-        };
-
-        private static string[] OrdinalTenthsPlus = {
-            "", "", "vingt", "trente", "quarante", "cinquante",
-            "soixante", "", "quatre-vingt", ""
-        };
-
-        public static string GetListItemText(string languageCultureName, int levelNumber, string numFmt)
-        {
-            if (numFmt == "cardinalText")
-            {
-                string result = "";
-
-                var sLevel = (levelNumber + 10000).ToString();
-                int thousands = int.Parse(sLevel.Substring(1, 1));
-                int hundreds = int.Parse(sLevel.Substring(2, 1));
-                int tens = int.Parse(sLevel.Substring(3, 1));
-                int ones = int.Parse(sLevel.Substring(4, 1));
-
-                /* exact thousands */
-                if (levelNumber == 1000)
-                    return "Mille";
-                if (levelNumber > 1000 && hundreds == 0 && tens == 0 && ones == 0)
-                {
-                    result = OneThroughNineteen[thousands] + " mille";
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                /* > 1000 */
-                if (levelNumber > 1000 && levelNumber < 2000)
-                    result = "mille ";
-                else if (levelNumber > 2000 && levelNumber < 10000)
-                    result = OneThroughNineteen[thousands] + " mille ";
-
-                /* exact hundreds */
-                if (hundreds > 0 && tens == 0 && ones == 0)
-                {
-                    if (hundreds == 1)
-                        result += "cent";
-                    else
-                        result += OneThroughNineteen[hundreds] + " cents";
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                /* > 100 */
-                if (hundreds > 0)
-                {
-                    if (hundreds == 1)
-                        result += "cent ";
-                    else
-                        result += OneThroughNineteen[hundreds] + " cent ";
-                }
-
-                /* exact tens */
-                if (tens > 0 && ones == 0)
-                {
-                    if (tens == 8)
-                        result += "quatre-vingts";
-                    else
-                        result += Tens[tens];
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                /* 71-79 */
-                if (tens == 7)
-                {
-                    if (ones == 1)
-                        result += Tens[6] + " et " + OneThroughNineteen[ones + 10];
-                    else
-                        result += Tens[6] + "-" + OneThroughNineteen[ones + 10];
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                /* 91-99 */
-                if (tens == 9)
-                {
-                    result += Tens[8] + "-" + OneThroughNineteen[ones + 10];
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                if (tens >= 2)
-                {
-                    if (ones == 1 && tens != 8 && tens != 9)
-                        result += Tens[tens] + " et un";
-                    else
-                        result += Tens[tens] + "-" + OneThroughNineteen[ones];
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                if (levelNumber < 20)
-                {
-                    result += OneThroughNineteen[tens * 10 + ones];
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                result += OneThroughNineteen[tens * 10 + ones];
-                return result.Substring(0, 1).ToUpper() + result.Substring(1);
-            }
-            if (numFmt == "ordinal")
-            {
-                string suffix;
-                if (levelNumber == 1)
-                    suffix = "er";
-                else
-                    suffix = "e";
-                return levelNumber.ToString() + suffix;
-            }
-            if (numFmt == "ordinalText")
-            {
-                string result = "";
-
-                if (levelNumber == 1)
-                    return "Premier";
-
-                var sLevel = (levelNumber + 10000).ToString();
-                int thousands = int.Parse(sLevel.Substring(1, 1));
-                int hundreds = int.Parse(sLevel.Substring(2, 1));
-                int tens = int.Parse(sLevel.Substring(3, 1));
-                int ones = int.Parse(sLevel.Substring(4, 1));
-
-                /* exact thousands */
-                if (levelNumber == 1000)
-                    return "Millième";
-                if (levelNumber > 1000 && hundreds == 0 && tens == 0 && ones == 0)
-                {
-                    result = OneThroughNineteen[thousands] + " millième";
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                /* > 1000 */
-                if (levelNumber > 1000 && levelNumber < 2000)
-                    result = "mille ";
-                else if (levelNumber > 2000 && levelNumber < 10000)
-                    result = OneThroughNineteen[thousands] + " mille ";
-
-                /* exact hundreds */
-                if (hundreds > 0 && tens == 0 && ones == 0)
-                {
-                    if (hundreds == 1)
-                        result += "centième";
-                    else
-                        result += OneThroughNineteen[hundreds] + " centième";
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                /* > 100 */
-                if (hundreds > 0)
-                {
-                    if (hundreds == 1)
-                        result += "cent ";
-                    else
-                        result += OneThroughNineteen[hundreds] + " cent ";
-                }
-
-                /* exact tens */
-                if (tens > 0 && ones == 0)
-                {
-                    result += OrdinalTenths[tens];
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                /* 71-79 */
-                if (tens == 7)
-                {
-                    if (ones == 1)
-                        result += OrdinalTenthsPlus[6] + " et " + OrdinalOneThroughNineteen[ones + 10];
-                    else
-                        result += OrdinalTenthsPlus[6] + "-" + OrdinalOneThroughNineteen[ones + 10];
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                /* 91-99 */
-                if (tens == 9)
-                {
-                    result += OrdinalTenthsPlus[8] + "-" + OrdinalOneThroughNineteen[ones + 10];
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                if (tens >= 2)
-                {
-                    if (ones == 1 && tens != 8 && tens != 9)
-                        result += OrdinalTenthsPlus[tens] + " et unième";
-                    else
-                        result += OrdinalTenthsPlus[tens] + "-" + OrdinalOneThroughNineteen[ones];
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                if (levelNumber < 20)
-                {
-                    result += OrdinalOneThroughNineteen[tens * 10 + ones];
-                    return result.Substring(0, 1).ToUpper() + result.Substring(1);
-                }
-
-                result += OrdinalOneThroughNineteen[tens * 10 + ones];
-                return result.Substring(0, 1).ToUpper() + result.Substring(1);
-            }
-            return null;
-        }
-    }
-}

+ 0 - 122
TEAMModelOS.SDK/Module/OpenXmlTool/GetListItemText_ru_RU.cs

@@ -1,122 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text;
-
-namespace OpenXmlPowerTools
-{
-    public class ListItemTextGetter_ru_RU
-    {
-        private static string[] OneThroughNineteen = {
-            "один", "два", "три", "четыре", "пять", "шесть", "семь", "восемь",
-            "девять", "десять", "одиннадцать", "двенадцать", "тринадцать", "четырнадцать",
-            "пятнадцать", "шестнадцать", "семнадцать", "восемнадцать", "девятнадцать"
-        };
-
-        private static string[] Tens = {
-            "десять", "двадцать", "тридцать", "сорок", "пятьдесят", "шестьдесят", "семьдесят",
-            "восемьдесят", "девяносто"
-        };
-
-        private static string[] OrdinalOneThroughNineteen = {
-            "первый", "второй", "третий", "четвертый", "пятый", "шестой",
-            "седьмой", "восьмой", "девятый", "десятый", "одиннадцатый", "двенадцатый",
-            "тринадцатый", "четырнадцатый", "пятнадцатый", "шестнадцатый",
-            "семнадцатый", "восемнадцатый", "девятнадцатый"
-        };
-
-        private static string[] OrdinalTenths = {
-            "десятый", "двадцатый", "тридцатый", "сороковой", "пятидесятый",
-            "шестидесятый", "семидесятый", "восьмидесятый", "девяностый"
-        };
-
-        // TODO this is not correct for values above 99
-
-        public static string GetListItemText(string languageCultureName, int levelNumber, string numFmt)
-        {
-            if (numFmt == "cardinalText")
-            {
-                string result = "";
-                int t1 = levelNumber / 1000;
-                int t2 = levelNumber % 1000;
-                if (t1 >= 1)
-                    result += OneThroughNineteen[t1 - 1] + " thousand";
-                if (t1 >= 1 && t2 == 0)
-                    return result.Substring(0, 1).ToUpper() +
-                        result.Substring(1);
-                if (t1 >= 1)
-                    result += " ";
-                int h1 = (levelNumber % 1000) / 100;
-                int h2 = levelNumber % 100;
-                if (h1 >= 1)
-                    result += OneThroughNineteen[h1 - 1] + " hundred";
-                if (h1 >= 1 && h2 == 0)
-                    return result.Substring(0, 1).ToUpper() +
-                        result.Substring(1);
-                if (h1 >= 1)
-                    result += " ";
-                int z = levelNumber % 100;
-                if (z <= 19)
-                    result += OneThroughNineteen[z - 1];
-                else
-                {
-                    int x = z / 10;
-                    int r = z % 10;
-                    result += Tens[x - 1];
-                    if (r >= 1)
-                        result += "-" + OneThroughNineteen[r - 1];
-                }
-                return result.Substring(0, 1).ToUpper() +
-                    result.Substring(1);
-            }
-            if (numFmt == "ordinalText")
-            {
-                string result = "";
-                int t1 = levelNumber / 1000;
-                int t2 = levelNumber % 1000;
-                if (t1 >= 1 && t2 != 0)
-                    result += OneThroughNineteen[t1 - 1] + " thousand";
-                if (t1 >= 1 && t2 == 0)
-                {
-                    result += OneThroughNineteen[t1 - 1] + " thousandth";
-                    return result.Substring(0, 1).ToUpper() +
-                        result.Substring(1);
-                }
-                if (t1 >= 1)
-                    result += " ";
-                int h1 = (levelNumber % 1000) / 100;
-                int h2 = levelNumber % 100;
-                if (h1 >= 1 && h2 != 0)
-                    result += OneThroughNineteen[h1 - 1] + " hundred";
-                if (h1 >= 1 && h2 == 0)
-                {
-                    result += OneThroughNineteen[h1 - 1] + " hundredth";
-                    return result.Substring(0, 1).ToUpper() +
-                        result.Substring(1);
-                }
-                if (h1 >= 1)
-                    result += " ";
-                int z = levelNumber % 100;
-                if (z <= 19)
-                    result += OrdinalOneThroughNineteen[z - 1];
-                else
-                {
-                    int x = z / 10;
-                    int r = z % 10;
-                    if (r == 0)
-                        result += OrdinalTenths[x - 1];
-                    else
-                        result += Tens[x - 1];
-                    if (r >= 1)
-                        result += " " + OrdinalOneThroughNineteen[r - 1];
-                }
-                return result.Substring(0, 1).ToUpper() +
-                    result.Substring(1);
-            }
-            return null;
-        }
-    }
-}

+ 0 - 213
TEAMModelOS.SDK/Module/OpenXmlTool/GetListItemText_sv_SE.cs

@@ -1,213 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text;
-
-namespace OpenXmlPowerTools
-{
-	public class ListItemTextGetter_sv_SE
-	{
-		private static string[] OneThroughNineteen = {
-            "", "ett", "två", "tre", "fyra", "fem", "sex", "sju", "åtta",
-            "nio", "tio", "elva", "tolv", "tretton", "fjorton",
-            "femton", "sexton", "sjutton", "arton", "nitton"
-        };
-
-		private static string[] Tens = {
-            "","tio", "tjugo", "trettio", "fyrtio", "femtio", "sextio", "sjuttio", "åttio",
-            "nittio", "etthundra"
-        };
-
-		private static string[] OrdinalOneThroughNineteen = {
-            "", "första", "andra", "tredje", "fjärde", "femte", "sjätte", "sjunde",
-            "åttonde", "nionde", "tionde", "elfte", "tolfte", "trettonde",
-            "fjortonde", "femtonde", "sextonde", "sjuttonde",
-            "artonde", "nittonde"
-        };
-
-		public static string GetListItemText(string languageCultureName, int levelNumber, string numFmt)
-		{
-			switch (numFmt)
-			{
-				case "cardinalText":
-					return NumberAsCardinalText(languageCultureName, levelNumber, numFmt);
-				case "ordinalText":
-					return NumberAsOrdinalText(languageCultureName, levelNumber, numFmt);
-				case "ordinal":
-					return NumberAsOrdinal(languageCultureName, levelNumber, numFmt);
-				default:
-					return null;
-			}
-		}
-		private static string NumberAsCardinalText(string languageCultureName, int levelNumber, string numFmt)
-		{
-			string result = "";
-
-			var sLevel = (levelNumber + 10000).ToString();
-			int thousands = int.Parse(sLevel.Substring(1, 1));
-			int hundreds = int.Parse(sLevel.Substring(2, 1));
-			int tens = int.Parse(sLevel.Substring(3, 1));
-			int ones = int.Parse(sLevel.Substring(4, 1));
-
-
-			//Validation
-			if (thousands > 19)
-				throw new ArgumentOutOfRangeException("levelNumber", "Convering a levelNumber to ordinal text that is greater then 19 999 is not supported");
-			if (levelNumber == 0)
-				return "Noll";
-			if (levelNumber < 0)
-				throw new ArgumentOutOfRangeException("levelNumber", "Converting a negative levelNumber to ordinal text is not supported");
-
-			/* exact thousands */
-			if (levelNumber == 1000)
-				return "Ettusen";
-			if (levelNumber > 1000 && hundreds == 0 && tens == 0 && ones == 0)
-			{
-				result = OneThroughNineteen[thousands] + "tusen";
-				return result.Substring(0, 1).ToUpper() + result.Substring(1);
-			}
-
-			/* > 1000 */
-			if (levelNumber > 1000 && levelNumber < 2000)
-				result = "ettusen";
-			else if (levelNumber > 2000 && levelNumber < 10000)
-				result = OneThroughNineteen[thousands] + "tusen";
-
-			/* exact hundreds */
-			if (hundreds > 0 && tens == 0 && ones == 0)
-			{
-				if (hundreds == 1)
-					result += "etthundra";
-				else
-					result += OneThroughNineteen[hundreds] + "hundra";
-				return result.Substring(0, 1).ToUpper() + result.Substring(1);
-			}
-
-			/* > 100 */
-			if (hundreds > 0)
-			{
-				if (hundreds == 1)
-					result += "etthundra";
-				else
-					result += OneThroughNineteen[hundreds] + "hundra";
-			}
-
-			/* exact tens */
-			if (tens > 0 && ones == 0)
-			{
-				result += Tens[tens];
-				return result.Substring(0, 1).ToUpper() + result.Substring(1);
-			}
-
-			/* > 20 */
-			if (tens == 1)
-			{
-				result += OneThroughNineteen[tens * 10 + ones];
-				return result.Substring(0, 1).ToUpper() + result.Substring(1);
-			}
-			else if (tens > 1)
-			{
-				result += Tens[tens] + OneThroughNineteen[ones]; ;
-				return result.Substring(0, 1).ToUpper() + result.Substring(1);
-			}
-			else
-			{
-				result += OneThroughNineteen[ones];
-				return result.Substring(0, 1).ToUpper() + result.Substring(1);
-			}
-		}
-		private static string NumberAsOrdinalText(string languageCultureName, int levelNumber, string numFmt)
-		{
-			string result = "";
-
-			if (levelNumber <= 0)
-				throw new ArgumentOutOfRangeException("levelNumber", "Converting a zero or negative levelNumber to ordinal text is not supported");
-			if(levelNumber >= 10000)
-				throw new ArgumentOutOfRangeException("levelNumber", "Convering a levelNumber to ordinal text that is greater then 10000 is not supported");
-
-			if (levelNumber == 1)
-				return "Första";
-
-			var sLevel = (levelNumber + 10000).ToString();
-			int thousands = int.Parse(sLevel.Substring(1, 1));
-			int hundreds = int.Parse(sLevel.Substring(2, 1));
-			int tens = int.Parse(sLevel.Substring(3, 1));
-			int ones = int.Parse(sLevel.Substring(4, 1));
-
-
-			/* exact thousands */
-			if (levelNumber == 1000)
-				return "Ettusende";
-			if (levelNumber > 1000 && hundreds == 0 && tens == 0 && ones == 0)
-			{
-				result = OneThroughNineteen[thousands] + "tusende";
-				return result.Substring(0, 1).ToUpper() + result.Substring(1);
-			}
-
-			/* > 1000 */
-			if (levelNumber > 1000 && levelNumber < 2000)
-				result = "ettusen";
-			else if (levelNumber > 2000 && levelNumber < 10000)
-				result = OneThroughNineteen[thousands] + "tusende";
-
-			/* exact hundreds */
-			if (hundreds > 0 && tens == 0 && ones == 0)
-			{
-				if (hundreds == 1)
-					result += "etthundrade";
-				else
-					result += OneThroughNineteen[hundreds] + "hundrade";
-				return result.Substring(0, 1).ToUpper() + result.Substring(1);
-			}
-
-			/* > 100 */
-			if (hundreds > 0)
-			{
-				result += OneThroughNineteen[hundreds] + "hundra";
-			}
-
-			/* exact tens */
-			if (tens > 0 && ones == 0)
-			{
-				result += Tens[tens] + "nde";
-				return result.Substring(0, 1).ToUpper() + result.Substring(1);
-			}
-
-			/* > 20 */
-			if (tens == 1)
-			{
-				result += OrdinalOneThroughNineteen[tens * 10 + ones];
-				return result.Substring(0, 1).ToUpper() + result.Substring(1);
-			}
-			else if (tens > 1)
-			{
-				result += Tens[tens] + OrdinalOneThroughNineteen[ones]; ;
-				return result.Substring(0, 1).ToUpper() + result.Substring(1);
-			}
-			else
-			{
-				result += OrdinalOneThroughNineteen[ones];
-				return result.Substring(0, 1).ToUpper() + result.Substring(1);
-			}
-		}
-		private static string NumberAsOrdinal(string languageCultureName, int levelNumber, string numFmt)
-		{
-			string levelAsString = levelNumber.ToString();
-
-            if (levelAsString == null)
-                return "";
-            if (levelAsString.Trim() == "")
-				return "";
-
-			if(levelAsString.EndsWith("1"))
-				return levelAsString + ":a";
-			else if(levelAsString.EndsWith("2"))
-				return levelAsString + ":a";
-			else
-				return levelAsString + ":e";
-		}
-	}
-}

+ 0 - 218
TEAMModelOS.SDK/Module/OpenXmlTool/GetListItemText_tr_TR.cs

@@ -1,218 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text;
-
-namespace OpenXmlPowerTools
-{
-    public class ListItemTextGetter_tr_TR
-    {
-        private static string[] RomanOnes =
-        {
-            "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"
-        };
-
-        private static string[] RomanTens =
-        {
-            "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"
-        };
-
-        private static string[] RomanHundreds =
-        {
-            "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "M"
-        };
-
-        private static string[] RomanThousands =
-        {
-            "", "M", "MM", "MMM", "MMMM", "MMMMM", "MMMMMM", "MMMMMMM", "MMMMMMMM",
-            "MMMMMMMMM", "MMMMMMMMMM"
-        };
-
-        private static string[] OneThroughNineteen = {
-            "bir", "iki", "üç", "dört", "beş", "altı", "yedi", "sekiz",
-            "dokuz", "on", "onbir", "oniki", "onüç", "ondört",
-            "onbeş", "onaltı", "onyedi", "onsekiz", "ondokuz"
-        };
-
-        private static string[] Tens = {
-            "on", "yirmi", "otuz", "kırk", "elli", "altmış", "yetmiş",
-            "seksen", "doksan"
-        };
-
-        private static string[] OrdinalOneThroughNineteen = {
-            "birinci", "ikinci", "üçüncü", "dördüncü", "beşinci", "altıncı",
-            "yedinci", "sekizinci", "dokuzuncu", "onuncu", "onbirinci", "onikinci",
-            "onüçüncü", "ondördüncü", "onbeşinci", "onaltıncı",
-            "onyedinci", "onsekizinci", "ondokuzuncu"
-        };
-
-        private static string[] TwoThroughNineteen = {
-            "", "iki", "üç", "dört", "beş", "altı", "yedi", "sekiz",
-            "dokuz", "on", "onbir", "oniki", "onüç", "ondört",
-            "onbeş", "onaltı", "onyedi", "onsekiz", "ondokuz"
-        };
-
-        private static string[] OrdinalTenths = {
-            "onuncu", "yirminci", "otuzuncu", "kırkıncı", "ellinci",
-            "altmışıncı", "yetmişinci", "sekseninci", "doksanıncı"
-        };
-
-        public static string GetListItemText(string languageCultureName, int levelNumber, string numFmt)
-        {
-            #region
-            if (numFmt == "decimal")
-            {
-                return levelNumber.ToString();
-            }
-            if (numFmt == "decimalZero")
-            {
-                if (levelNumber <= 9)
-                    return "0" + levelNumber.ToString();
-                else
-                    return levelNumber.ToString();
-            }
-            if (numFmt == "upperRoman")
-            {
-                int ones = levelNumber % 10;
-                int tens = (levelNumber % 100) / 10;
-                int hundreds = (levelNumber % 1000) / 100;
-                int thousands = levelNumber / 1000;
-                return RomanThousands[thousands] + RomanHundreds[hundreds] +
-                    RomanTens[tens] + RomanOnes[ones];
-            }
-            if (numFmt == "lowerRoman")
-            {
-                int ones = levelNumber % 10;
-                int tens = (levelNumber % 100) / 10;
-                int hundreds = (levelNumber % 1000) / 100;
-                int thousands = levelNumber / 1000;
-                return (RomanThousands[thousands] + RomanHundreds[hundreds] +
-                    RomanTens[tens] + RomanOnes[ones]).ToLower();
-            }
-            if (numFmt == "upperLetter")
-            {
-                string a = "ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ";
-                //string a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-                int c = (levelNumber - 1) / 29;
-                int n = (levelNumber - 1) % 29;
-                char x = a[n];
-                return "".PadRight(c + 1, x);
-            }
-            if (numFmt == "lowerLetter")
-            {
-                string a = "abcçdefgğhıijklmnoöprsştuüvyz";
-                int c = (levelNumber - 1) / 29;
-                int n = (levelNumber - 1) % 29;
-                char x = a[n];
-                return "".PadRight(c + 1, x);
-            }
-            if (numFmt == "ordinal")
-            {
-                string suffix;
-                /*if (levelNumber % 100 == 11 || levelNumber % 100 == 12 ||
-                    levelNumber % 100 == 13)
-                    suffix = "th";
-                else if (levelNumber % 10 == 1)
-                    suffix = "st";
-                else if (levelNumber % 10 == 2)
-                    suffix = "nd";
-                else if (levelNumber % 10 == 3)
-                    suffix = "rd";
-                else
-                    suffix = "th";*/
-                suffix = ".";
-                return levelNumber.ToString() + suffix;
-            }
-            if (numFmt == "cardinalText")
-            {
-                string result = "";
-                int t1 = levelNumber / 1000;
-                int t2 = levelNumber % 1000;
-                if (t1 >= 1)
-                    result += OneThroughNineteen[t1 - 1] + " yüz";
-                if (t1 >= 1 && t2 == 0)
-                    return result.Substring(0, 1).ToUpper() +
-                        result.Substring(1);
-                if (t1 >= 1)
-                    result += " ";
-                int h1 = (levelNumber % 1000) / 100;
-                int h2 = levelNumber % 100;
-                if (h1 >= 1)
-                    result += OneThroughNineteen[h1 - 1] + " bin";
-                if (h1 >= 1 && h2 == 0)
-                    return result.Substring(0, 1).ToUpper() +
-                        result.Substring(1);
-                if (h1 >= 1)
-                    result += " ";
-                int z = levelNumber % 100;
-                if (z <= 19)
-                    result += OneThroughNineteen[z - 1];
-                else
-                {
-                    int x = z / 10;
-                    int r = z % 10;
-                    result += Tens[x - 1];
-                    if (r >= 1)
-                        result += /*"-" + */OneThroughNineteen[r - 1];
-                }
-                return result.Substring(0, 1).ToUpper() +
-                    result.Substring(1);
-            }
-            #endregion
-            if (numFmt == "ordinalText")
-            {
-                string result = "";
-                int t1 = levelNumber / 1000;
-                int t2 = levelNumber % 1000;
-                if (t1 >= 1 && t2 != 0)
-                    result += TwoThroughNineteen[t1 - 1] + "bin";
-                if (t1 >= 1 && t2 == 0)
-                {
-                    result += TwoThroughNineteen[t1 - 1] + "bininci";
-                    return result.Substring(0, 1).ToUpper() +
-                        result.Substring(1);
-                }
-                //if (t1 >= 1)
-                //    result += " ";
-                int h1 = (levelNumber % 1000) / 100;
-                int h2 = levelNumber % 100;
-                if (h1 >= 1 && h2 != 0)
-                    result += TwoThroughNineteen[h1 - 1] + "yüz";
-                if (h1 >= 1 && h2 == 0)
-                {
-                    result += TwoThroughNineteen[h1 - 1] + "yüzüncü";
-                    return result.Substring(0, 1).ToUpper() +
-                        result.Substring(1);
-                }
-                //if (h1 >= 1)
-                //    result += " ";
-                int z = levelNumber % 100;
-                if (z <= 19)
-                    result += OrdinalOneThroughNineteen[z - 1];
-                else
-                {
-                    int x = z / 10;
-                    int r = z % 10;
-                    if (r == 0)
-                        result += OrdinalTenths[x - 1];
-                    else
-                        result += Tens[x - 1];
-                    if (r >= 1)
-                        result += OrdinalOneThroughNineteen[r - 1]; //result += "-" + OrdinalOneThroughNineteen[r - 1];
-                }
-                return result.Substring(0, 1).ToUpper() +
-                    result.Substring(1);
-            }
-            if (numFmt == "0001, 0002, 0003, ...")
-            {
-                return string.Format("{0:0000}", levelNumber);
-            }
-            if (numFmt == "bullet")
-                return "";
-            return levelNumber.ToString();
-        }
-    }
-}

+ 0 - 130
TEAMModelOS.SDK/Module/OpenXmlTool/GetListItemText_zh_CN.cs

@@ -1,130 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text;
-
-namespace OpenXmlPowerTools
-{
-    public class ListItemTextGetter_zh_CN
-    {
-        public static string GetListItemText(string languageCultureName, int levelNumber, string numFmt)
-        {
-            string[] ccTDigitCharacters = new[] {
-                "",
-                "一",
-                "二",
-                "三",
-                "四",
-                "五",
-                "六",
-                "七",
-                "八",
-                "九",
-            };
-            string tenCharacter = "十";
-            string hundredCharacter = "百";
-            string thousandCharacter = "千";
-            string andCharacter = "〇";
-
-            string[] ccDigitCharacters = new[] {
-                "○",
-                "一",
-                "二",
-                "三",
-                "四",
-                "五",
-                "六",
-                "七",
-                "八",
-                "九",
-            };
-
-            int thousandsRemainder = levelNumber % 1000;
-            int hundredsRemainder = levelNumber % 100;
-            int thousands = levelNumber / 1000;
-            int hundreds = (levelNumber % 1000) / 100;
-            int tens = (levelNumber % 100) / 10;
-            int ones = levelNumber % 10;
-
-            if (numFmt == "chineseCounting")
-            {
-                if (levelNumber >= 1 && levelNumber <= 9)
-                    return ccDigitCharacters[levelNumber];
-                if (levelNumber >= 10 && levelNumber <= 19)
-                {
-                    if (levelNumber == 10)
-                        return tenCharacter;
-                    return tenCharacter + ccDigitCharacters[ones];
-                }
-                if (levelNumber >= 11 && levelNumber <= 99)
-                {
-                    if (ones == 0)
-                        return ccDigitCharacters[tens] + tenCharacter;
-                    return ccDigitCharacters[tens] + tenCharacter + ccDigitCharacters[ones];
-                }
-                if (levelNumber >= 100 && levelNumber <= 999)
-                    return ccDigitCharacters[hundreds] + ccDigitCharacters[tens] + ccDigitCharacters[ones];
-                if (levelNumber >= 1000 && levelNumber <= 9999)
-                    return ccDigitCharacters[thousands] + ccDigitCharacters[hundreds] + ccDigitCharacters[tens] + ccDigitCharacters[ones];
-                return levelNumber.ToString();
-            }
-            if (numFmt == "chineseCountingThousand")
-            {
-                if (levelNumber >= 1 && levelNumber <= 9)
-                    return ccTDigitCharacters[levelNumber];
-                if (levelNumber >= 10 && levelNumber <= 19)
-                    return tenCharacter + ccTDigitCharacters[ones];
-                if (levelNumber >= 20 && levelNumber <= 99)
-                    return ccTDigitCharacters[tens] + tenCharacter + ccTDigitCharacters[ones];
-                if (levelNumber >= 100 && levelNumber <= 999)
-                {
-                    if (hundredsRemainder == 0)
-                        return ccTDigitCharacters[hundreds] + hundredCharacter;
-                    if (hundredsRemainder >= 1 && hundredsRemainder <= 9)
-                        return ccTDigitCharacters[hundreds] + hundredCharacter + andCharacter + ccTDigitCharacters[levelNumber % 10];
-                    if (ones == 0)
-                        return ccTDigitCharacters[hundreds] + hundredCharacter + ccTDigitCharacters[tens] + tenCharacter;
-                    return ccTDigitCharacters[hundreds] + hundredCharacter + ccTDigitCharacters[tens] + tenCharacter + ccTDigitCharacters[ones];
-                }
-                if (levelNumber >= 1000 && levelNumber <= 9999)
-                {
-                    if (thousandsRemainder == 0)
-                        return ccTDigitCharacters[thousands] + thousandCharacter;
-                    if (thousandsRemainder >= 1 && thousandsRemainder <= 9)
-                        return ccTDigitCharacters[thousands] + thousandCharacter + andCharacter + GetListItemText("zh_CN", thousandsRemainder, numFmt);
-                    if (thousandsRemainder >= 10 && thousandsRemainder <= 99)
-                        return ccTDigitCharacters[thousands] + thousandCharacter + andCharacter + ccTDigitCharacters[tens] + tenCharacter + ccTDigitCharacters[ones];
-                    if (hundredsRemainder == 0)
-                        return ccTDigitCharacters[thousands] + thousandCharacter + ccTDigitCharacters[hundreds] + hundredCharacter;
-                    if (hundredsRemainder >= 1 && hundredsRemainder <= 9)
-                        return ccTDigitCharacters[thousands] + thousandCharacter + ccTDigitCharacters[hundreds] + hundredCharacter + andCharacter + ccTDigitCharacters[ones];
-                    return ccTDigitCharacters[thousands] + thousandCharacter + ccTDigitCharacters[hundreds] + hundredCharacter + ccTDigitCharacters[tens] + tenCharacter + ccTDigitCharacters[ones];
-                }
-                return levelNumber.ToString();
-            }
-            if (numFmt == "ideographTraditional")
-            {
-                string[] iDigitCharacters = new[] {
-                    " ",
-                    "甲",
-                    "乙",
-                    "丙",
-                    "丁",
-                    "戊",
-                    "己",
-                    "庚",
-                    "辛",
-                    "壬",
-                    "癸",
-                };
-                if (levelNumber >= 1 && levelNumber <= 10)
-                    return iDigitCharacters[levelNumber];
-                return levelNumber.ToString();
-            }
-            return null;
-        }
-    }
-}

+ 0 - 533
TEAMModelOS.SDK/Module/OpenXmlTool/HtmlToWmlConverter.cs

@@ -1,533 +0,0 @@
-// 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.Generic;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-using OpenXmlPowerTools;
-using OpenXmlPowerTools.HtmlToWml;
-using OpenXmlPowerTools.HtmlToWml.CSS;
-using System.Text.RegularExpressions;
-
-namespace OpenXmlPowerTools
-{
-    public class HtmlToWmlConverterSettings
-    {
-        public string MajorLatinFont;
-        public string MinorLatinFont;
-        public double DefaultFontSize;
-        public XElement DefaultSpacingElement;
-        public XElement DefaultSpacingElementForParagraphsInTables;
-        public XElement SectPr;
-        public string DefaultBlockContentMargin;
-        public string BaseUriForImages;
-
-        public Twip PageWidthTwips { get { return (long)SectPr.Elements(W.pgSz).Attributes(W._w).FirstOrDefault(); } }
-        public Twip PageMarginLeftTwips { get { return (long)SectPr.Elements(W.pgMar).Attributes(W.left).FirstOrDefault(); } }
-        public Twip PageMarginRightTwips { get { return (long)SectPr.Elements(W.pgMar).Attributes(W.right).FirstOrDefault(); } }
-        public Emu PageWidthEmus { get { return Emu.TwipsToEmus(PageWidthTwips); } }
-        public Emu PageMarginLeftEmus { get { return Emu.TwipsToEmus(PageMarginLeftTwips); } }
-        public Emu PageMarginRightEmus { get { return Emu.TwipsToEmus(PageMarginRightTwips); } }
-    }
-
-    public class HtmlToWmlConverter
-    {
-        public static WmlDocument ConvertHtmlToWml(
-            string defaultCss,
-            string authorCss,
-            string userCss,
-            XElement xhtml,
-            HtmlToWmlConverterSettings settings)
-        {
-            return HtmlToWmlConverterCore.ConvertHtmlToWml(defaultCss, authorCss, userCss, xhtml, settings, null, null);
-        }
-
-        public static WmlDocument ConvertHtmlToWml(
-            string defaultCss,
-            string authorCss,
-            string userCss,
-            XElement xhtml,
-            HtmlToWmlConverterSettings settings,
-            WmlDocument emptyDocument,
-            string annotatedHtmlDumpFileName)
-        {
-            return HtmlToWmlConverterCore.ConvertHtmlToWml(defaultCss, authorCss, userCss, xhtml, settings, emptyDocument, annotatedHtmlDumpFileName);
-        }
-
-        private static string s_Blank_wml_base64 = @"UEsDBBQABgAIAAAAIQAJJIeCgQEAAI4FAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAAC
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC0
-lE1Pg0AQhu8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AQItABQABgAIAAAA
-IQAXoBZOAgEAAKwBAAAUAAAAAAAAAAAAAAAAAB0XAAB3b3JkL3dlYlNldHRpbmdzLnhtbFBLAQIt
-ABQABgAIAAAAIQCAS4U32AgAAAJCAAAaAAAAAAAAAAAAAAAAAFEYAAB3b3JkL3N0eWxlc1dpdGhF
-ZmZlY3RzLnhtbFBLAQItABQABgAIAAAAIQDt7KzfewEAAN8CAAARAAAAAAAAAAAAAAAAAGEhAABk
-b2NQcm9wcy9jb3JlLnhtbFBLAQItABQABgAIAHWCpUBDMZvdBAkAAIJEAAAPAAAAAAAAAAAAAAAA
-ABMkAAB3b3JkL3N0eWxlcy54bWxQSwECLQAUAAYACAAAACEATbb2nsIBAACiBAAAEgAAAAAAAAAA
-AAAAAABELQAAd29yZC9mb250VGFibGUueG1sUEsBAi0AFAAGAAgAAAAhAE5wytZwAQAAxQIAABAA
-AAAAAAAAAAAAAAAANi8AAGRvY1Byb3BzL2FwcC54bWxQSwUGAAAAAAwADAAJAwAA3DEAAAAA";
-
-        private static WmlDocument s_EmptyDocument = null;
-
-        public static WmlDocument EmptyDocument
-        {
-            get {
-                if (s_EmptyDocument == null)
-                {
-                    s_EmptyDocument = new WmlDocument("EmptyDocument.docx", Convert.FromBase64String(s_Blank_wml_base64));
-                }
-                return s_EmptyDocument;
-            }
-        }
-
-        public static HtmlToWmlConverterSettings GetDefaultSettings()
-        {
-            return GetDefaultSettings(EmptyDocument);
-        }
-
-        public static HtmlToWmlConverterSettings GetDefaultSettings(WmlDocument wmlDocument)
-        {
-            HtmlToWmlConverterSettings settings = new HtmlToWmlConverterSettings();
-            using (MemoryStream ms = new MemoryStream())
-            {
-                ms.Write(wmlDocument.DocumentByteArray, 0, wmlDocument.DocumentByteArray.Length);
-                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, false))
-                {
-                    string majorLatinFont, minorLatinFont;
-                    double defaultFontSize;
-                    GetDefaultFontInfo(wDoc, out majorLatinFont, out minorLatinFont, out defaultFontSize);
-                    settings.MajorLatinFont = majorLatinFont;
-                    settings.MinorLatinFont = minorLatinFont;
-                    settings.DefaultFontSize = defaultFontSize;
-
-                    settings.MinorLatinFont = "Times New Roman";
-                    settings.DefaultFontSize = 12d;
-                    settings.DefaultBlockContentMargin = "auto";
-                    settings.DefaultSpacingElement = new XElement(W.spacing,
-                        new XAttribute(W.before, 100),
-                        new XAttribute(W.beforeAutospacing, 1),
-                        new XAttribute(W.after, 100),
-                        new XAttribute(W.afterAutospacing, 1),
-                        new XAttribute(W.line, 240),
-                        new XAttribute(W.lineRule, "auto"));
-                    settings.DefaultSpacingElementForParagraphsInTables = new XElement(W.spacing,
-                        new XAttribute(W.before, 100),
-                        new XAttribute(W.beforeAutospacing, 1),
-                        new XAttribute(W.after, 100),
-                        new XAttribute(W.afterAutospacing, 1),
-                        new XAttribute(W.line, 240),
-                        new XAttribute(W.lineRule, "auto"));
-
-                    XDocument mXDoc = wDoc.MainDocumentPart.GetXDocument();
-                    XElement existingSectPr = mXDoc.Root.Descendants(W.sectPr).FirstOrDefault();
-                    settings.SectPr = new XElement(W.sectPr,
-                        existingSectPr.Elements(W.pgSz),
-                        existingSectPr.Elements(W.pgMar));
-                }
-            }
-            return settings;
-        }
-
-        private static void GetDefaultFontInfo(WordprocessingDocument wDoc, out string majorLatinFont, out string minorLatinFont, out double defaultFontSize)
-        {
-            if (wDoc.MainDocumentPart.ThemePart != null)
-            {
-                XElement fontScheme = wDoc.MainDocumentPart.ThemePart.GetXDocument().Root.Elements(A.themeElements).Elements(A.fontScheme).FirstOrDefault();
-                if (fontScheme != null)
-                {
-                    majorLatinFont = (string)fontScheme.Elements(A.majorFont).Elements(A.latin).Attributes(NoNamespace.typeface).FirstOrDefault();
-                    minorLatinFont = (string)fontScheme.Elements(A.minorFont).Elements(A.latin).Attributes(NoNamespace.typeface).FirstOrDefault();
-                    string defaultFontSizeString = (string)wDoc.MainDocumentPart.StyleDefinitionsPart.GetXDocument().Root.Elements(W.docDefaults)
-                        .Elements(W.rPrDefault).Elements(W.rPr).Elements(W.sz).Attributes(W.val).FirstOrDefault();
-                    if (defaultFontSizeString != null)
-                    {
-                        double dfs;
-                        if (double.TryParse(defaultFontSizeString, out dfs))
-                        {
-                            defaultFontSize = dfs / 2d;
-                            return;
-                        }
-                        defaultFontSize = 12;
-                        return;
-                    }
-                }
-            }
-            majorLatinFont = "";
-            minorLatinFont = "";
-            defaultFontSize = 12;
-        }
-
-        public static string CleanUpCss(string css)
-        {
-            if (css == null)
-                return "";
-            css = css.Trim();
-            string cleanCss = Regex.Split(css, "\r\n|\r|\n")
-                .Where(l =>
-                {
-                    string lTrim = l.Trim();
-                    if (lTrim == "//")
-                        return false;
-                    if (lTrim == "////")
-                        return false;
-                    if (lTrim == "<!--" || lTrim == "&lt;!--")
-                        return false;
-                    if (lTrim == "-->" || lTrim == "--&gt;")
-                        return false;
-                    return true;
-                })
-                .Select(l => l + Environment.NewLine )
-                .StringConcatenate();
-            return cleanCss;
-        }
-    }
-
-    public struct Emu
-    {
-        public long m_Value;
-        public static int s_EmusPerInch = 914400;
-
-        public static Emu TwipsToEmus(long twips)
-        {
-            float v1 = (float)twips / 20f;
-            float v2 = v1 / 72f;
-            float v3 = v2 * s_EmusPerInch;
-            long emus = (long)v3;
-            return new Emu(emus);
-        }
-
-        public static Emu PointsToEmus(double points)
-        {
-            double v1 = points / 72;
-            double v2 = v1 * s_EmusPerInch;
-            long emus = (long)v2;
-            return new Emu(emus);
-        }
-
-        public Emu(long value)
-        {
-            m_Value = value;
-        }
-
-        public static implicit operator long(Emu e)
-        {
-            return e.m_Value;
-        }
-
-        public static implicit operator Emu(long l)
-        {
-            return new Emu(l);
-        }
-
-        public override string ToString()
-        {
-            throw new OpenXmlPowerToolsException("Can't convert directly to string, must cast to long");
-        }
-    }
-
-    public struct TPoint
-    {
-        public double m_Value;
-
-        public TPoint(double value)
-        {
-            m_Value = value;
-        }
-
-        public static implicit operator double(TPoint t)
-        {
-            return t.m_Value;
-        }
-
-        public static implicit operator TPoint(double d)
-        {
-            return new TPoint(d);
-        }
-
-        public override string ToString()
-        {
-            throw new OpenXmlPowerToolsException("Can't convert directly to string, must cast to double");
-        }
-    }
-
-    public struct Twip
-    {
-        public long m_Value;
-
-        public Twip(long value)
-        {
-            m_Value = value;
-        }
-
-        public static implicit operator long(Twip t)
-        {
-            return t.m_Value;
-        }
-
-        public static implicit operator Twip(long l)
-        {
-            return new Twip(l);
-        }
-
-        public static implicit operator Twip(double d)
-        {
-            return new Twip((long)d);
-        }
-
-        public override string ToString()
-        {
-            throw new OpenXmlPowerToolsException("Can't convert directly to string, must cast to long");
-        }
-    }
-
-    public class SizeEmu
-    {
-        public Emu m_Height;
-        public Emu m_Width;
-
-        public SizeEmu(Emu width, Emu height)
-        {
-            m_Width = width;
-            m_Height = height;
-        }
-
-        public SizeEmu(long width, long height)
-        {
-            m_Width = width;
-            m_Height = height;
-        }
-    }
-}
-

文件差異過大導致無法顯示
+ 0 - 5359
TEAMModelOS.SDK/Module/OpenXmlTool/HtmlToWmlConverterCore.cs


文件差異過大導致無法顯示
+ 0 - 3743
TEAMModelOS.SDK/Module/OpenXmlTool/HtmlToWmlCssApplier.cs


文件差異過大導致無法顯示
+ 0 - 4388
TEAMModelOS.SDK/Module/OpenXmlTool/HtmlToWmlCssParser.cs


文件差異過大導致無法顯示
+ 0 - 1169
TEAMModelOS.SDK/Module/OpenXmlTool/ListItemRetriever.cs


+ 0 - 692
TEAMModelOS.SDK/Module/OpenXmlTool/MarkupSimplifier.cs

@@ -1,692 +0,0 @@
-// 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.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.Xml.Linq;
-using System.Xml.Schema;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public partial class WmlDocument
-    {
-        public WmlDocument SimplifyMarkup(SimplifyMarkupSettings settings)
-        {
-            return MarkupSimplifier.SimplifyMarkup(this, settings);
-        }
-    }
-
-    public class SimplifyMarkupSettings
-    {
-        public bool AcceptRevisions;
-        public bool NormalizeXml;
-        public bool RemoveBookmarks;
-        public bool RemoveComments;
-        public bool RemoveContentControls;
-        public bool RemoveEndAndFootNotes;
-        public bool RemoveFieldCodes;
-        public bool RemoveGoBackBookmark;
-        public bool RemoveHyperlinks;
-        public bool RemoveLastRenderedPageBreak;
-        public bool RemoveMarkupForDocumentComparison;
-        public bool RemovePermissions;
-        public bool RemoveProof;
-        public bool RemoveRsidInfo;
-        public bool RemoveSmartTags;
-        public bool RemoveSoftHyphens;
-        public bool RemoveWebHidden;
-        public bool ReplaceTabsWithSpaces;
-    }
-
-    [SuppressMessage("ReSharper", "InconsistentNaming")]
-    public static class MarkupSimplifier
-    {
-        public static WmlDocument SimplifyMarkup(WmlDocument doc, SimplifyMarkupSettings settings)
-        {
-            using (var streamDoc = new OpenXmlMemoryStreamDocument(doc))
-            {
-                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
-                    SimplifyMarkup(document, settings);
-                return streamDoc.GetModifiedWmlDocument();
-            }
-        }
-
-        public static void SimplifyMarkup(WordprocessingDocument doc, SimplifyMarkupSettings settings)
-        {
-            if (settings.RemoveMarkupForDocumentComparison)
-            {
-                settings.RemoveRsidInfo = true;
-                RemoveElementsForDocumentComparison(doc);
-            }
-            if (settings.RemoveRsidInfo)
-                RemoveRsidInfoInSettings(doc);
-            if (settings.AcceptRevisions)
-                RevisionAccepter.AcceptRevisions(doc);
-            foreach (OpenXmlPart part in doc.ContentParts())
-                SimplifyMarkupForPart(part, settings);
-
-            if (doc.MainDocumentPart.StyleDefinitionsPart != null)
-                SimplifyMarkupForPart(doc.MainDocumentPart.StyleDefinitionsPart, settings);
-            if (doc.MainDocumentPart.StylesWithEffectsPart != null)
-                SimplifyMarkupForPart(doc.MainDocumentPart.StylesWithEffectsPart, settings);
-
-            if (settings.RemoveComments)
-            {
-                WordprocessingCommentsPart commentsPart = doc.MainDocumentPart.WordprocessingCommentsPart;
-                if (commentsPart != null) doc.MainDocumentPart.DeletePart(commentsPart);
-
-                WordprocessingCommentsExPart commentsExPart = doc.MainDocumentPart.WordprocessingCommentsExPart;
-                if (commentsExPart != null) doc.MainDocumentPart.DeletePart(commentsExPart);
-            }
-        }
-
-        private static void RemoveRsidInfoInSettings(WordprocessingDocument doc)
-        {
-            DocumentSettingsPart part = doc.MainDocumentPart.DocumentSettingsPart;
-            if (part == null) return;
-
-            XDocument settingsXDoc = part.GetXDocument();
-            settingsXDoc.Descendants(W.rsids).Remove();
-            part.PutXDocument();
-        }
-
-        private static void RemoveElementsForDocumentComparison(WordprocessingDocument doc)
-        {
-            OpenXmlPart part = doc.ExtendedFilePropertiesPart;
-            if (part != null)
-            {
-                XDocument appPropsXDoc = part.GetXDocument();
-                appPropsXDoc.Descendants(EP.TotalTime).Remove();
-                part.PutXDocument();
-            }
-
-            part = doc.CoreFilePropertiesPart;
-            if (part != null)
-            {
-                XDocument corePropsXDoc = part.GetXDocument();
-                corePropsXDoc.Descendants(CP.revision).Remove();
-                corePropsXDoc.Descendants(DCTERMS.created).Remove();
-                corePropsXDoc.Descendants(DCTERMS.modified).Remove();
-                part.PutXDocument();
-            }
-
-            XDocument mainXDoc = doc.MainDocumentPart.GetXDocument();
-            List<XElement> bookmarkStart = mainXDoc
-                .Descendants(W.bookmarkStart)
-                .Where(b => (string) b.Attribute(W.name) == "_GoBack")
-                .ToList();
-            foreach (XElement item in bookmarkStart)
-            {
-                IEnumerable<XElement> bookmarkEnd = mainXDoc
-                    .Descendants(W.bookmarkEnd)
-                    .Where(be => (int) be.Attribute(W.id) == (int) item.Attribute(W.id));
-                bookmarkEnd.Remove();
-            }
-
-            bookmarkStart.Remove();
-            doc.MainDocumentPart.PutXDocument();
-        }
-
-        public static XElement MergeAdjacentSuperfluousRuns(XElement element)
-        {
-            return (XElement) MergeAdjacentRunsTransform(element);
-        }
-
-        public static XElement TransformElementToSingleCharacterRuns(XElement element)
-        {
-            return (XElement) SingleCharacterRunTransform(element);
-        }
-
-        public static void TransformPartToSingleCharacterRuns(OpenXmlPart part)
-        {
-            // After transforming to single character runs, Rsid info will be invalid, so
-            // remove from the part.
-            XDocument xDoc = part.GetXDocument();
-            var newRoot = (XElement) RemoveRsidTransform(xDoc.Root);
-            newRoot = (XElement) SingleCharacterRunTransform(newRoot);
-            xDoc.Elements().First().ReplaceWith(newRoot);
-            part.PutXDocument();
-        }
-
-        public static void TransformToSingleCharacterRuns(WordprocessingDocument doc)
-        {
-            if (RevisionAccepter.HasTrackedRevisions(doc))
-                throw new OpenXmlPowerToolsException(
-                    "Transforming a document to single character runs is not supported for " +
-                    "a document with tracked revisions.");
-
-            foreach (OpenXmlPart part in doc.ContentParts())
-                TransformPartToSingleCharacterRuns(part);
-        }
-
-        private static object RemoveCustomXmlAndContentControlsTransform(
-            XNode node, SimplifyMarkupSettings simplifyMarkupSettings)
-        {
-            XElement element = node as XElement;
-            if (element != null)
-            {
-                if (simplifyMarkupSettings.RemoveSmartTags &&
-                    element.Name == W.smartTag)
-                    return element
-                        .Elements()
-                        .Select(e =>
-                            RemoveCustomXmlAndContentControlsTransform(e,
-                                simplifyMarkupSettings));
-
-                if (simplifyMarkupSettings.RemoveContentControls &&
-                    element.Name == W.sdt)
-                    return element
-                        .Elements(W.sdtContent)
-                        .Elements()
-                        .Select(e =>
-                            RemoveCustomXmlAndContentControlsTransform(e,
-                                simplifyMarkupSettings));
-
-                return new XElement(element.Name,
-                    element.Attributes(),
-                    element.Nodes().Select(n => RemoveCustomXmlAndContentControlsTransform(n, simplifyMarkupSettings)));
-            }
-
-            return node;
-        }
-
-        private static object RemoveRsidTransform(XNode node)
-        {
-            var element = node as XElement;
-            if (element == null) return node;
-
-            if (element.Name == W.rsid)
-                return null;
-
-            return new XElement(element.Name,
-                element
-                    .Attributes()
-                    .Where(a => (a.Name != W.rsid) &&
-                                (a.Name != W.rsidDel) &&
-                                (a.Name != W.rsidP) &&
-                                (a.Name != W.rsidR) &&
-                                (a.Name != W.rsidRDefault) &&
-                                (a.Name != W.rsidRPr) &&
-                                (a.Name != W.rsidSect) &&
-                                (a.Name != W.rsidTr)),
-                element.Nodes().Select(n => RemoveRsidTransform(n)));
-        }
-
-        private static object MergeAdjacentRunsTransform(XNode node)
-        {
-            var element = node as XElement;
-            if (element == null) return node;
-
-            if (element.Name == W.p)
-                return WordprocessingMLUtil.CoalesceAdjacentRunsWithIdenticalFormatting(element);
-
-            return new XElement(element.Name,
-                element.Attributes(),
-                element.Nodes().Select(n => MergeAdjacentRunsTransform(n)));
-        }
-
-        private static object RemoveEmptyRunsAndRunPropertiesTransform(
-            XNode node)
-        {
-            var element = node as XElement;
-            if (element != null)
-            {
-                if (((element.Name == W.r) || (element.Name == W.rPr) || (element.Name == W.pPr)) &&
-                    !element.Elements().Any())
-                    return null;
-
-                return new XElement(element.Name,
-                    element.Attributes(),
-                    element.Nodes().Select(n => RemoveEmptyRunsAndRunPropertiesTransform(n)));
-            }
-
-            return node;
-        }
-
-        private static object MergeAdjacentInstrText(
-            XNode node)
-        {
-            var element = node as XElement;
-            if (element != null)
-            {
-                if ((element.Name == W.r) && element.Elements(W.instrText).Any())
-                {
-                    IEnumerable<IGrouping<bool, XElement>> grouped =
-                        element.Elements().GroupAdjacent(e => e.Name == W.instrText);
-                    return new XElement(W.r,
-                        grouped.Select(g =>
-                        {
-                            if (g.Key == false)
-                                return (object) g;
-
-                            // If .doc files are converted to .docx by the Binary to Open XML Translator,
-                            // the w:instrText elements might be empty, in which case newInstrText would
-                            // be an empty string.
-                            string newInstrText = g.Select(i => (string) i).StringConcatenate();
-                            if (string.IsNullOrEmpty(newInstrText))
-                                return new XElement(W.instrText);
-
-                            return new XElement(W.instrText,
-                                (newInstrText[0] == ' ') || (newInstrText[newInstrText.Length - 1] == ' ')
-                                    ? new XAttribute(XNamespace.Xml + "space", "preserve")
-                                    : null,
-                                newInstrText);
-                        }));
-                }
-
-                return new XElement(element.Name,
-                    element.Attributes(),
-                    element.Nodes().Select(n => MergeAdjacentInstrText(n)));
-            }
-
-            return node;
-        }
-
-        // lastRenderedPageBreak, permEnd, permStart, proofErr, noProof
-        // softHyphen:
-        // Remove when simplifying.
-
-        // fldSimple, fldData, fldChar, instrText:
-        // For hyperlinks, generate same in XHtml.  Other than hyperlinks, do the following:
-        // - collapse fldSimple
-        // - remove fldSimple, fldData, fldChar, instrText.
-
-        private static object SimplifyMarkupTransform(
-            XNode node,
-            SimplifyMarkupSettings settings,
-            SimplifyMarkupParameters parameters)
-        {
-            var element = node as XElement;
-            if (element == null) return node;
-
-            if (settings.RemovePermissions &&
-                ((element.Name == W.permEnd) ||
-                 (element.Name == W.permStart)))
-                return null;
-
-            if (settings.RemoveProof &&
-                ((element.Name == W.proofErr) ||
-                 (element.Name == W.noProof)))
-                return null;
-
-            if (settings.RemoveSoftHyphens &&
-                (element.Name == W.softHyphen))
-                return null;
-
-            if (settings.RemoveLastRenderedPageBreak &&
-                (element.Name == W.lastRenderedPageBreak))
-                return null;
-
-            if (settings.RemoveBookmarks &&
-                ((element.Name == W.bookmarkStart) ||
-                 (element.Name == W.bookmarkEnd)))
-                return null;
-
-            if (settings.RemoveGoBackBookmark &&
-                (((element.Name == W.bookmarkStart) && ((int) element.Attribute(W.id) == parameters.GoBackId)) ||
-                 ((element.Name == W.bookmarkEnd) && ((int) element.Attribute(W.id) == parameters.GoBackId))))
-                return null;
-
-            if (settings.RemoveWebHidden &&
-                (element.Name == W.webHidden))
-                return null;
-
-            if (settings.ReplaceTabsWithSpaces &&
-                (element.Name == W.tab) && 
-                (element.Parent != null && element.Parent.Name == W.r))
-                return new XElement(W.t, new XAttribute(XNamespace.Xml + "space", "preserve"), " ");
-
-            if (settings.RemoveComments &&
-                ((element.Name == W.commentRangeStart) ||
-                 (element.Name == W.commentRangeEnd) ||
-                 (element.Name == W.commentReference) ||
-                 (element.Name == W.annotationRef)))
-                return null;
-
-            if (settings.RemoveComments &&
-                (element.Name == W.rStyle) &&
-                (element.Attribute(W.val).Value == "CommentReference"))
-                return null;
-
-            if (settings.RemoveEndAndFootNotes &&
-                ((element.Name == W.endnoteReference) ||
-                 (element.Name == W.footnoteReference)))
-                return null;
-
-            if (settings.RemoveFieldCodes)
-            {
-                if (element.Name == W.fldSimple)
-                    return element.Elements().Select(e => SimplifyMarkupTransform(e, settings, parameters));
-
-                if ((element.Name == W.fldData) ||
-                    (element.Name == W.fldChar) ||
-                    (element.Name == W.instrText))
-                    return null;
-            }
-
-            if (settings.RemoveHyperlinks &&
-                (element.Name == W.hyperlink))
-                return element.Elements();
-
-            return new XElement(element.Name,
-                element.Attributes(),
-                element.Nodes().Select(n => SimplifyMarkupTransform(n, settings, parameters)));
-        }
-
-        private static XDocument Normalize(XDocument source, XmlSchemaSet schema)
-        {
-            var 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;
-
-                    var e = n as XElement;
-                    return e != null ? NormalizeElement(e, havePsvi) : n;
-                }));
-        }
-
-        // TODO: Check whether this can be removed.
-        //private 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)
-                    {
-                        IXmlSchemaInfo schemaInfo = a.GetSchemaInfo();
-                        XmlSchemaType schemaType = schemaInfo != null ? schemaInfo.SchemaType : null;
-                        XmlTypeCode? typeCode = schemaType != null ? schemaType.TypeCode : (XmlTypeCode?) null;
-
-                        switch (typeCode)
-                        {
-                            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;
-
-            var 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)
-            {
-                IXmlSchemaInfo schemaInfo = element.GetSchemaInfo();
-                XmlSchemaType schemaType = schemaInfo != null ? schemaInfo.SchemaType : null;
-                XmlTypeCode? typeCode = schemaType != null ? schemaType.TypeCode : (XmlTypeCode?) null;
-
-                switch (typeCode)
-                {
-                    case XmlTypeCode.Boolean:
-                        return new XElement(element.Name,
-                            NormalizeAttributes(element, true),
-                            (bool) element);
-                    case XmlTypeCode.DateTime:
-                        return new XElement(element.Name,
-                            NormalizeAttributes(element, true),
-                            (DateTime) element);
-                    case XmlTypeCode.Decimal:
-                        return new XElement(element.Name,
-                            NormalizeAttributes(element, true),
-                            (decimal) element);
-                    case XmlTypeCode.Double:
-                        return new XElement(element.Name,
-                            NormalizeAttributes(element, true),
-                            (double) element);
-                    case XmlTypeCode.Float:
-                        return new XElement(element.Name,
-                            NormalizeAttributes(element, true),
-                            (float) element);
-                    case XmlTypeCode.HexBinary:
-                    case XmlTypeCode.Language:
-                        return new XElement(element.Name,
-                            NormalizeAttributes(element, true),
-                            ((string) element).ToLower());
-                    default:
-                        return new XElement(element.Name,
-                            NormalizeAttributes(element, true),
-                            element.Nodes().Select(n => NormalizeNode(n, true)));
-                }
-            }
-
-            return new XElement(element.Name,
-                NormalizeAttributes(element, false),
-                element.Nodes().Select(n => NormalizeNode(n, false)));
-        }
-
-        private static void SimplifyMarkupForPart(OpenXmlPart part, SimplifyMarkupSettings settings)
-        {
-            var parameters = new SimplifyMarkupParameters();
-            if (part.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml")
-            {
-                var doc = (WordprocessingDocument) part.OpenXmlPackage;
-                if (settings.RemoveGoBackBookmark)
-                {
-                    XElement goBackBookmark = doc
-                        .MainDocumentPart
-                        .GetXDocument()
-                        .Descendants(W.bookmarkStart)
-                        .FirstOrDefault(bm => (string) bm.Attribute(W.name) == "_GoBack");
-                    if (goBackBookmark != null)
-                        parameters.GoBackId = (int) goBackBookmark.Attribute(W.id);
-                }
-            }
-
-            XDocument xdoc = part.GetXDocument();
-            XElement newRoot = xdoc.Root;
-
-            // Need to do this first to enable simplifying hyperlinks.
-            if (settings.RemoveContentControls || settings.RemoveSmartTags)
-                newRoot = (XElement) RemoveCustomXmlAndContentControlsTransform(newRoot, settings);
-
-            // This may touch many elements, so needs to be its own transform.
-            if (settings.RemoveRsidInfo)
-                newRoot = (XElement) RemoveRsidTransform(newRoot);
-
-            var prevNewRoot = new XDocument(newRoot);
-            while (true)
-            {
-                if (settings.RemoveComments ||
-                    settings.RemoveEndAndFootNotes ||
-                    settings.ReplaceTabsWithSpaces ||
-                    settings.RemoveFieldCodes ||
-                    settings.RemovePermissions ||
-                    settings.RemoveProof ||
-                    settings.RemoveBookmarks ||
-                    settings.RemoveWebHidden ||
-                    settings.RemoveGoBackBookmark ||
-                    settings.RemoveHyperlinks)
-                    newRoot = (XElement) SimplifyMarkupTransform(newRoot, settings, parameters);
-
-                // Remove runs and run properties that have become empty due to previous transforms.
-                newRoot = (XElement) RemoveEmptyRunsAndRunPropertiesTransform(newRoot);
-
-                // Merge adjacent runs that have identical run properties.
-                newRoot = (XElement) MergeAdjacentRunsTransform(newRoot);
-
-                // Merge adjacent instrText elements.
-                newRoot = (XElement) MergeAdjacentInstrText(newRoot);
-
-                // Separate run children into separate runs
-                newRoot = (XElement) SeparateRunChildrenIntoSeparateRuns(newRoot);
-
-                if (XNode.DeepEquals(prevNewRoot.Root, newRoot))
-                    break;
-
-                prevNewRoot = new XDocument(newRoot);
-            }
-
-            if (settings.NormalizeXml)
-            {
-                XAttribute[] nsAttrs =
-                {
-                    new XAttribute(XNamespace.Xmlns + "wpc", WPC.wpc),
-                    new XAttribute(XNamespace.Xmlns + "mc", MC.mc),
-                    new XAttribute(XNamespace.Xmlns + "o", O.o),
-                    new XAttribute(XNamespace.Xmlns + "r", R.r),
-                    new XAttribute(XNamespace.Xmlns + "m", M.m),
-                    new XAttribute(XNamespace.Xmlns + "v", VML.vml),
-                    new XAttribute(XNamespace.Xmlns + "wp14", WP14.wp14),
-                    new XAttribute(XNamespace.Xmlns + "wp", WP.wp),
-                    new XAttribute(XNamespace.Xmlns + "w10", W10.w10),
-                    new XAttribute(XNamespace.Xmlns + "w", W.w),
-                    new XAttribute(XNamespace.Xmlns + "w14", W14.w14),
-                    new XAttribute(XNamespace.Xmlns + "w15", W15.w15),
-                    new XAttribute(XNamespace.Xmlns + "w16se", W16SE.w16se),
-                    new XAttribute(XNamespace.Xmlns + "wpg", WPG.wpg),
-                    new XAttribute(XNamespace.Xmlns + "wpi", WPI.wpi),
-                    new XAttribute(XNamespace.Xmlns + "wne", WNE.wne),
-                    new XAttribute(XNamespace.Xmlns + "wps", WPS.wps),
-                    new XAttribute(MC.Ignorable, "w14 wp14 w15 w16se"),
-                };
-
-                XDocument newXDoc = Normalize(new XDocument(newRoot), null);
-                newRoot = newXDoc.Root;
-                if (newRoot != null)
-                    foreach (XAttribute nsAttr in nsAttrs)
-                        if (newRoot.Attribute(nsAttr.Name) == null)
-                            newRoot.Add(nsAttr);
-
-                part.PutXDocument(newXDoc);
-            }
-            else
-            {
-                part.PutXDocument(new XDocument(newRoot));
-            }
-        }
-
-        private static object SeparateRunChildrenIntoSeparateRuns(XNode node)
-        {
-            var element = node as XElement;
-            if (element == null) return node;
-
-            if (element.Name == W.r)
-            {
-                IEnumerable<XElement> runChildren = element.Elements().Where(e => e.Name != W.rPr);
-                XElement rPr = element.Element(W.rPr);
-                return runChildren.Select(rc => new XElement(W.r, rPr, rc));
-            }
-
-            return new XElement(element.Name,
-                element.Attributes(),
-                element.Nodes().Select(n => SeparateRunChildrenIntoSeparateRuns(n)));
-        }
-
-        private static object SingleCharacterRunTransform(XNode node)
-        {
-            var element = node as XElement;
-            if (element == null) return node;
-
-            if (element.Name == W.r)
-                return element.Elements()
-                    .Where(e => e.Name != W.rPr)
-                    .GroupAdjacent(sr => sr.Name == W.t)
-                    .Select(g =>
-                    {
-                        if (g.Key)
-                        {
-                            string s = g.Select(t => (string) t).StringConcatenate();
-                            return s.Select(c =>
-                                new XElement(W.r,
-                                    element.Elements(W.rPr),
-                                    new XElement(W.t,
-                                        c == ' ' ? new XAttribute(XNamespace.Xml + "space", "preserve") : null,
-                                        c)));
-                        }
-
-                        return g.Select(sr =>
-                            new XElement(W.r,
-                                element.Elements(W.rPr),
-                                new XElement(sr.Name,
-                                    sr.Attributes(),
-                                    sr.Nodes().Select(n => SingleCharacterRunTransform(n)))));
-                    });
-
-            return new XElement(element.Name,
-                element.Attributes(),
-                element.Nodes().Select(n => SingleCharacterRunTransform(n)));
-        }
-
-        private static class Xsi
-        {
-            private static readonly XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
-
-            public static readonly XName schemaLocation = xsi + "schemaLocation";
-            public static readonly XName noNamespaceSchemaLocation = xsi + "noNamespaceSchemaLocation";
-        }
-
-        public class InternalException : Exception
-        {
-            public InternalException(string message) : base(message)
-            {
-            }
-        }
-
-        public class InvalidSettingsException : Exception
-        {
-            public InvalidSettingsException(string message) : base(message)
-            {
-            }
-        }
-
-        private class SimplifyMarkupParameters
-        {
-            public int? GoBackId { get; set; }
-        }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 1071
TEAMModelOS.SDK/Module/OpenXmlTool/MetricsGetter.cs


+ 0 - 562
TEAMModelOS.SDK/Module/OpenXmlTool/OpenXmlRegex.cs

@@ -1,562 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text.RegularExpressions;
-using System.Xml.Linq;
-
-namespace OpenXmlPowerTools
-{
-    public class OpenXmlRegex
-    {
-        private const string DontConsolidate = "DontConsolidate";
-
-        private static readonly HashSet<XName> RevTrackMarkupWithId = new HashSet<XName>
-        {
-            W.cellDel,
-            W.cellIns,
-            W.cellMerge,
-            W.customXmlDelRangeEnd,
-            W.customXmlDelRangeStart,
-            W.customXmlInsRangeEnd,
-            W.customXmlInsRangeStart,
-            W.customXmlMoveFromRangeEnd,
-            W.customXmlMoveFromRangeStart,
-            W.customXmlMoveToRangeEnd,
-            W.customXmlMoveToRangeStart,
-            W.del,
-            W.ins,
-            W.moveFrom,
-            W.moveFromRangeEnd,
-            W.moveFromRangeStart,
-            W.moveTo,
-            W.moveToRangeEnd,
-            W.moveToRangeStart,
-            W.pPrChange,
-            W.rPrChange,
-            W.sectPrChange,
-            W.tblGridChange,
-            W.tblPrChange,
-            W.tblPrExChange,
-            W.tcPrChange
-        };
-
-        public static int Match(IEnumerable<XElement> content, Regex regex)
-        {
-            return ReplaceInternal(content, regex, null, null, false, null, true);
-        }
-
-        /// <summary>
-        /// If callback == null Then returns count of matches in the content
-        /// If callback != null Then Match calls Found for each match
-        /// </summary>
-        public static int Match(IEnumerable<XElement> content, Regex regex, Action<XElement, Match> found)
-        {
-            return ReplaceInternal(content, regex, null,
-                (x, m) =>
-                {
-                    if (found != null) found.Invoke(x, m);
-                    return true;
-                },
-                false, null, true);
-        }
-
-        /// <summary>
-        /// If replacement == "new content" && callback == null
-        ///     Then replaces all matches
-        /// If replacement == "" && callback == null)
-        ///     Then deletes all matches
-        /// If replacement == "new content" && callback != null)
-        ///     Then the callback can return true / false to indicate whether to replace or not
-        /// If the callback returns true once, and false on all subsequent calls, then this method replaces only the first found.
-        /// If replacement == "" && callback != null)
-        ///     Then the callback can return true / false to indicate whether to delete or not
-        /// </summary>
-        public static int Replace(IEnumerable<XElement> content, Regex regex, string replacement,
-            Func<XElement, Match, bool> doReplacement)
-        {
-            return ReplaceInternal(content, regex, replacement, doReplacement, false, null, true);
-        }
-
-        /// <summary>
-        /// This overload enables not coalescing content, which is necessary for DocumentAssembler.
-        /// </summary>
-        public static int Replace(IEnumerable<XElement> content, Regex regex, string replacement,
-            Func<XElement, Match, bool> doReplacement, bool coalesceContent)
-        {
-            return ReplaceInternal(content, regex, replacement, doReplacement, false, null, coalesceContent);
-        }
-
-        /// <summary>
-        /// If replacement == "new content" && callback == null
-        ///     Then replaces all matches
-        /// If replacement == "" && callback == null)
-        ///     Then deletes all matches
-        /// If replacement == "new content" && callback != null)
-        ///     Then the callback can return true / false to indicate whether to replace or not
-        /// If the callback returns true once, and false on all subsequent calls, then this method replaces only the first found.
-        /// If replacement == "" && callback != null)
-        ///     Then the callback can return true / false to indicate whether to delete or not
-        /// If trackRevisions == true
-        ///     Then replacement is done using revision tracking markup, with author as the revision tracking author
-        /// If trackRevisions == true for a PPTX
-        ///     Then code throws an exception
-        /// </summary>
-        public static int Replace(IEnumerable<XElement> content, Regex regex, string replacement,
-            Func<XElement, Match, bool> doReplacement, bool trackRevisions, string author)
-        {
-            return ReplaceInternal(content, regex, replacement, doReplacement, trackRevisions, author, true);
-        }
-
-        private static int ReplaceInternal(IEnumerable<XElement> content, Regex regex, string replacement,
-            Func<XElement, Match, bool> callback, bool trackRevisions, string revisionTrackingAuthor,
-            bool coalesceContent)
-        {
-            if (content == null) throw new ArgumentNullException("content");
-            if (regex == null) throw new ArgumentNullException("regex");
-
-            IEnumerable<XElement> contentList = content as IList<XElement> ?? content.ToList();
-
-            XElement first = contentList.FirstOrDefault();
-            if (first == null)
-                return 0;
-
-            if (first.Name.Namespace == W.w)
-            {
-                if (!contentList.Any())
-                    return 0;
-
-                var replInfo = new ReplaceInternalInfo { Count = 0 };
-                foreach (XElement c in contentList)
-                {
-                    var newC = (XElement) WmlSearchAndReplaceTransform(c, regex, replacement, callback, trackRevisions,
-                        revisionTrackingAuthor, replInfo, coalesceContent);
-                    c.ReplaceNodes(newC.Nodes());
-                }
-
-                XElement root = contentList.First().AncestorsAndSelf().Last();
-                int nextId = new[] { 0 }
-                                 .Concat(root
-                                     .Descendants()
-                                     .Where(d => RevTrackMarkupWithId.Contains(d.Name))
-                                     .Attributes(W.id)
-                                     .Select(a => (int) a))
-                                 .Max() + 1;
-                IEnumerable<XElement> revTrackingWithoutId = root
-                    .DescendantsAndSelf()
-                    .Where(d => RevTrackMarkupWithId.Contains(d.Name) && (d.Attribute(W.id) == null));
-                foreach (XElement item in revTrackingWithoutId)
-                    item.Add(new XAttribute(W.id, nextId++));
-
-                List<IGrouping<int, XElement>> revTrackingWithDuplicateIds = root
-                    .DescendantsAndSelf()
-                    .Where(d => RevTrackMarkupWithId.Contains(d.Name))
-                    .GroupBy(d => (int) d.Attribute(W.id))
-                    .Where(g => g.Count() > 1)
-                    .ToList();
-                foreach (IGrouping<int, XElement> group in revTrackingWithDuplicateIds)
-                    foreach (XElement gc in group.Skip(1))
-                    {
-                        XAttribute xAttribute = gc.Attribute(W.id);
-                        if (xAttribute != null) xAttribute.Value = nextId.ToString();
-                        nextId++;
-                    }
-
-                return replInfo.Count;
-            }
-
-            if ((first.Name.Namespace == P.p) || (first.Name.Namespace == A.a))
-            {
-                if (trackRevisions)
-                    throw new OpenXmlPowerToolsException("PPTX does not support revision tracking");
-
-                var counter = new ReplaceInternalInfo { Count = 0 };
-                foreach (XElement c in contentList)
-                {
-                    var newC = (XElement) PmlSearchAndReplaceTransform(c, regex, replacement, callback, counter);
-                    c.ReplaceNodes(newC.Nodes());
-                }
-
-                return counter.Count;
-            }
-
-            return 0;
-        }
-
-        private static object WmlSearchAndReplaceTransform(XNode node, Regex regex, string replacement,
-            Func<XElement, Match, bool> callback, bool trackRevisions, string revisionTrackingAuthor,
-            ReplaceInternalInfo replInfo, bool coalesceContent)
-        {
-            var element = node as XElement;
-            if (element == null) return node;
-
-            if (element.Name == W.p)
-            {
-                XElement paragraph = element;
-
-                string preliminaryContent = paragraph
-                    .DescendantsTrimmed(W.txbxContent)
-                    .Where(d => d.Name == W.r && (d.Parent == null || d.Parent.Name != W.del))
-                    .Select(UnicodeMapper.RunToString)
-                    .StringConcatenate();
-                if (regex.IsMatch(preliminaryContent))
-                {
-                    var paragraphWithSplitRuns = new XElement(W.p,
-                        paragraph.Attributes(),
-                        paragraph.Nodes().Select(n => WmlSearchAndReplaceTransform(n, regex, replacement, callback,
-                            trackRevisions, revisionTrackingAuthor, replInfo, coalesceContent)));
-
-                    IEnumerable<XElement> runsTrimmed = paragraphWithSplitRuns
-                        .DescendantsTrimmed(W.txbxContent)
-                        .Where(d => d.Name == W.r && (d.Parent == null || d.Parent.Name != W.del));
-
-                    var charsAndRuns = runsTrimmed
-                        .Select(r => new { Ch = UnicodeMapper.RunToString(r), r })
-                        .ToList();
-
-                    string content = charsAndRuns.Select(t => t.Ch).StringConcatenate();
-                    XElement[] alignedRuns = charsAndRuns.Select(t => t.r).ToArray();
-
-                    MatchCollection matchCollection = regex.Matches(content);
-                    replInfo.Count += matchCollection.Count;
-
-                    // Process Match
-                    if (replacement == null)
-                    {
-                        if (callback == null) return paragraph;
-
-                        foreach (Match match in matchCollection.Cast<Match>())
-                            callback(paragraph, match);
-
-                        return paragraph;
-                    }
-
-                    // Process Replace
-                    foreach (Match match in matchCollection.Cast<Match>())
-                    {
-                        if (match.Length == 0) continue;
-                        if ((callback != null) && !callback(paragraph, match)) continue;
-
-                        List<XElement> runCollection = alignedRuns
-                            .Skip(match.Index)
-                            .Take(match.Length)
-                            .ToList();
-
-                        // uses the Skip / Take special semantics of array to implement efficient finding of sub array
-
-                        XElement firstRun = runCollection.First();
-                        XElement firstRunProperties = firstRun.Elements(W.rPr).FirstOrDefault();
-
-                        // save away first run properties
-
-                        if (trackRevisions)
-                        {
-                            if (replacement != "")
-                            {
-                                // We coalesce runs as some methods, e.g., in DocumentAssembler,
-                                // will try to find the replacement string even though they
-                                // set coalesceContent to false.
-                                string newTextValue = match.Result(replacement);
-                                List<XElement> newRuns = UnicodeMapper.StringToCoalescedRunList(newTextValue,
-                                    firstRunProperties);
-                                var newIns = new XElement(W.ins,
-                                    new XAttribute(W.author, revisionTrackingAuthor),
-                                    new XAttribute(W.date, DateTime.UtcNow.ToString("s") + "Z"),
-                                    newRuns);
-
-                                if (firstRun.Parent != null && firstRun.Parent.Name == W.ins)
-                                    firstRun.Parent.AddBeforeSelf(newIns);
-                                else
-                                    firstRun.AddBeforeSelf(newIns);
-                            }
-
-                            foreach (XElement run in runCollection)
-                            {
-                                bool isInIns = run.Parent != null && run.Parent.Name == W.ins;
-                                if (isInIns)
-                                {
-                                    XElement parentIns = run.Parent;
-                                    XElement grandParentParagraph = parentIns.Parent;
-                                    if (grandParentParagraph != null)
-                                    {
-                                        if ((string) parentIns.Attributes(W.author).FirstOrDefault() ==
-                                            revisionTrackingAuthor)
-                                        {
-                                            List<XElement> parentInsSiblings = grandParentParagraph
-                                                .Elements()
-                                                .Where(c => c != parentIns)
-                                                .ToList();
-                                            grandParentParagraph.ReplaceNodes(parentInsSiblings);
-                                        }
-                                        else
-                                        {
-                                            List<XElement> parentInsSiblings = grandParentParagraph
-                                                .Elements()
-                                                .Select(c => c == parentIns
-                                                    ? new XElement(W.ins,
-                                                        parentIns.Attributes(),
-                                                        new XElement(W.del,
-                                                            new XAttribute(W.author, revisionTrackingAuthor),
-                                                            new XAttribute(W.date, DateTime.UtcNow.ToString("s") + "Z"),
-                                                            parentIns.Elements().Select(TransformToDelText)))
-                                                    : c)
-                                                .ToList();
-                                            grandParentParagraph.ReplaceNodes(parentInsSiblings);
-                                        }
-                                    }
-                                }
-                                else
-                                {
-                                    var delRun = new XElement(W.del,
-                                        new XAttribute(W.author, revisionTrackingAuthor),
-                                        new XAttribute(W.date, DateTime.UtcNow.ToString("s") + "Z"),
-                                        TransformToDelText(run));
-                                    run.ReplaceWith(delRun);
-                                }
-                            }
-                        }
-                        else // not tracked revisions
-                        {
-                            foreach (XElement runToDelete in runCollection.Skip(1).ToList())
-                                if (runToDelete.Parent != null && runToDelete.Parent.Name == W.ins)
-                                    runToDelete.Parent.Remove();
-                                else
-                                    runToDelete.Remove();
-
-                            // We coalesce runs as some methods, e.g., in DocumentAssembler,
-                            // will try to find the replacement string even though they
-                            // set coalesceContent to false.
-                            string newTextValue = match.Result(replacement);
-                            List<XElement> newRuns = UnicodeMapper.StringToCoalescedRunList(newTextValue,
-                                firstRunProperties);
-                            if (firstRun.Parent != null && firstRun.Parent.Name == W.ins)
-                                firstRun.Parent.ReplaceWith(newRuns);
-                            else
-                                firstRun.ReplaceWith(newRuns);
-                        }
-                    }
-
-                    return coalesceContent
-                        ? WordprocessingMLUtil.CoalesceAdjacentRunsWithIdenticalFormatting(paragraphWithSplitRuns)
-                        : paragraphWithSplitRuns;
-                }
-
-                var newParagraph = new XElement(W.p,
-                    paragraph.Attributes(),
-                    paragraph.Nodes().Select(n =>
-                    {
-                        var e = n as XElement;
-                        if (e == null) return n;
-
-                        if (e.Name == W.pPr)
-                            return e;
-                        if (((e.Name == W.r) && e.Elements(W.t).Any()) || e.Elements(W.tab).Any())
-                            return e;
-                        if ((e.Name == W.ins) && e.Elements(W.r).Elements(W.t).Any())
-                            return e;
-
-                        return WmlSearchAndReplaceTransform(e, regex, replacement, callback,
-                            trackRevisions, revisionTrackingAuthor, replInfo, coalesceContent);
-                    }));
-                return coalesceContent
-                    ? WordprocessingMLUtil.CoalesceAdjacentRunsWithIdenticalFormatting(newParagraph) // CoalesceContent(newParagraph)
-                    : newParagraph;
-            }
-
-            if (element.Name == W.ins && element.Elements(W.r).Any())
-            {
-                List<object> collectionOfCollections = element
-                    .Elements()
-                    .Select(n => WmlSearchAndReplaceTransform(n, regex, replacement, callback, trackRevisions,
-                        revisionTrackingAuthor, replInfo, coalesceContent))
-                    .ToList();
-                List<object> collectionOfIns = collectionOfCollections
-                    .Select(c =>
-                    {
-                        var elements = c as IEnumerable<XElement>;
-                        return elements != null
-                            ? elements.Select(ixc => new XElement(W.ins, element.Attributes(), ixc))
-                            : c;
-                    })
-                    .ToList();
-                return collectionOfIns;
-            }
-
-            if (element.Name == W.r)
-            {
-                return element.Elements()
-                    .Where(e => e.Name != W.rPr)
-                    .Select(e => e.Name == W.t
-                        ? ((string) e).Select(c =>
-                            new XElement(W.r,
-                                element.Elements(W.rPr),
-                                new XElement(W.t, XmlUtil.GetXmlSpaceAttribute(c), c)))
-                        : new[] { new XElement(W.r, element.Elements(W.rPr), e) })
-                    .SelectMany(t => t);
-            }
-
-            return new XElement(element.Name,
-                element.Attributes(),
-                element.Nodes()
-                    .Select(n => WmlSearchAndReplaceTransform(n, regex, replacement, callback, trackRevisions,
-                        revisionTrackingAuthor, replInfo, coalesceContent)));
-        }
-
-        private static object TransformToDelText(XNode node)
-        {
-            var element = node as XElement;
-            if (element == null) return node;
-
-            if (element.Name == W.t)
-                return new XElement(W.delText,
-                    XmlUtil.GetXmlSpaceAttribute(element.Value),
-                    element.Value);
-
-            return new XElement(element.Name,
-                element.Attributes(),
-                element.Nodes().Select(TransformToDelText));
-        }
-
-        private static object PmlSearchAndReplaceTransform(XNode node, Regex regex, string replacement,
-            Func<XElement, Match, bool> callback, ReplaceInternalInfo counter)
-        {
-            var element = node as XElement;
-            if (element == null) return node;
-
-            if (element.Name == A.p)
-            {
-                XElement paragraph = element;
-                string contents = element.Descendants(A.t).Select(t => (string) t).StringConcatenate();
-                if (!regex.IsMatch(contents))
-                    return new XElement(element.Name, element.Attributes(), element.Nodes());
-
-                var paragraphWithSplitRuns = new XElement(A.p,
-                    paragraph.Attributes(),
-                    paragraph.Nodes()
-                        .Select(n => PmlSearchAndReplaceTransform(n, regex, replacement, callback, counter)));
-
-                List<XElement> runsTrimmed = paragraphWithSplitRuns
-                    .Descendants(A.r)
-                    .ToList();
-
-                var charsAndRuns = runsTrimmed
-                    .Select(r =>
-                        r.Element(A.t) != null
-                            ? new { Ch = r.Element(A.t).Value, r }
-                            : new { Ch = "\x01", r })
-                    .ToList();
-
-                string content = charsAndRuns.Select(t => t.Ch).StringConcatenate();
-                XElement[] alignedRuns = charsAndRuns.Select(t => t.r).ToArray();
-
-                MatchCollection matchCollection = regex.Matches(content);
-                counter.Count += matchCollection.Count;
-                if (replacement == null)
-                {
-                    foreach (Match match in matchCollection.Cast<Match>())
-                        callback(paragraph, match);
-                }
-                else
-                {
-                    foreach (Match match in matchCollection.Cast<Match>())
-                    {
-                        if ((callback != null) && !callback(paragraph, match)) continue;
-
-                        List<XElement> runCollection = alignedRuns
-                            .Skip(match.Index)
-                            .Take(match.Length)
-                            .ToList();
-
-                        // uses the Skip / Take special semantics of array to implement efficient finding of sub array
-
-                        XElement firstRun = runCollection.First();
-
-                        // save away first run because we want the run properties
-
-                        runCollection.Skip(1).Remove();
-
-                        // binds to Remove(this IEnumerable<XElement> elements), which is an extension
-
-                        // in LINQ to XML that uses snapshot semantics and removes every element from
-                        // its parent.
-
-                        var newFirstRun = new XElement(A.r,
-                            firstRun.Element(A.rPr),
-                            new XElement(A.t, replacement));
-
-                        // creates a new run with proper run properties
-
-                        firstRun.ReplaceWith(newFirstRun);
-
-                        // finds firstRun in its parent's list of children, unparents firstRun,
-
-                        // sets newFirstRun's parent to firstRuns old parent, and inserts in the list
-                        // of children at the right place.
-                    }
-                    XElement paragraphWithReplacedRuns = paragraphWithSplitRuns;
-
-                    IEnumerable<IGrouping<string, XElement>> groupedAdjacentRunsWithIdenticalFormatting =
-                        paragraphWithReplacedRuns
-                            .Elements()
-                            .GroupAdjacent(ce =>
-                            {
-                                if (ce.Name != A.r)
-                                    return DontConsolidate;
-                                if ((ce.Elements().Count(e => e.Name != A.rPr) != 1) || (ce.Element(A.t) == null))
-                                    return DontConsolidate;
-
-                                XElement rPr = ce.Element(A.rPr);
-                                return rPr == null ? "" : rPr.ToString(SaveOptions.None);
-                            });
-                    var paragraphWithConsolidatedRuns = new XElement(A.p,
-                        groupedAdjacentRunsWithIdenticalFormatting.Select(g =>
-                        {
-                            if (g.Key == DontConsolidate)
-                                return (object) g;
-
-                            string textValue = g.Select(r => r.Element(A.t).Value).StringConcatenate();
-                            XAttribute xs = XmlUtil.GetXmlSpaceAttribute(textValue);
-                            return new XElement(A.r,
-                                g.First().Elements(A.rPr),
-                                new XElement(A.t, xs, textValue));
-                        }));
-                    paragraph = paragraphWithConsolidatedRuns;
-                }
-
-                return paragraph;
-            }
-
-            if ((element.Name == A.r) && element.Elements(A.t).Any())
-            {
-                return element.Elements()
-                    .Where(e => e.Name != A.rPr)
-                    .Select(e =>
-                    {
-                        if (e.Name == A.t)
-                        {
-                            var s = (string) e;
-                            IEnumerable<XElement> collectionOfSubRuns = s.Select(c => new XElement(A.r,
-                                element.Elements(A.rPr),
-                                new XElement(A.t, XmlUtil.GetXmlSpaceAttribute(c), c)));
-                            return (object) collectionOfSubRuns;
-                        }
-
-                        return new XElement(A.r,
-                            element.Elements(A.rPr),
-                            e);
-                    });
-            }
-
-            return new XElement(element.Name,
-                element.Attributes(),
-                element.Nodes().Select(n => PmlSearchAndReplaceTransform(n, regex, replacement, callback, counter)));
-        }
-
-        private class ReplaceInternalInfo
-        {
-            public int Count;
-        }
-    }
-}

+ 0 - 679
TEAMModelOS.SDK/Module/OpenXmlTool/OxPtHelpers.cs

@@ -1,679 +0,0 @@
-// 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.Generic;
-using System.Drawing;
-using System.IO;
-using System.Linq;
-using System.Xml;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-using DocumentFormat.OpenXml.Wordprocessing;
-using DocumentFormat.OpenXml.Validation;
-using OpenXmlPowerTools;
-using System.Text;
-using DocumentFormat.OpenXml;
-using System.Drawing.Imaging;
-
-namespace OpenXmlPowerTools
-{
-    public static class AddDocxTextHelper
-    {
-        public static WmlDocument AppendParagraphToDocument(
-            WmlDocument wmlDoc,
-            string strParagraph,
-            bool isBold,
-            bool isItalic,
-            bool isUnderline,
-            string foreColor,
-            string backColor,
-            string styleName)
-        {
-            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(wmlDoc))
-            {
-                using (WordprocessingDocument wDoc = streamDoc.GetWordprocessingDocument())
-                {
-                    StyleDefinitionsPart part = wDoc.MainDocumentPart.StyleDefinitionsPart;
-
-                    Body body = wDoc.MainDocumentPart.Document.Body;
-
-                    SectionProperties sectionProperties = body.Elements<SectionProperties>().FirstOrDefault();
-
-                    Paragraph paragraph = new Paragraph();
-                    Run run = paragraph.AppendChild(new Run());
-                    RunProperties runProperties = new RunProperties();
-
-                    if (isBold)
-                        runProperties.AppendChild(new Bold());
-
-                    if (isItalic)
-                        runProperties.AppendChild(new Italic());
-
-
-                    if (!string.IsNullOrEmpty(foreColor))
-                    {
-                        int colorValue = ColorParser.FromName(foreColor).ToArgb();
-                        if (colorValue == 0)
-                            throw new OpenXmlPowerToolsException(String.Format("Add-DocxText: The specified color {0} is unsupported, Please specify the valid color. Ex, Red, Green", foreColor));
-
-                        string ColorHex = string.Format("{0:x6}", colorValue);
-                        runProperties.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = ColorHex.Substring(2) });
-                    }
-
-                    if (isUnderline)
-                        runProperties.AppendChild(new Underline() { Val = UnderlineValues.Single });
-
-                    if (!string.IsNullOrEmpty(backColor))
-                    {
-                        int colorShade = ColorParser.FromName(backColor).ToArgb();
-                        if (colorShade == 0)
-                            throw new OpenXmlPowerToolsException(String.Format("Add-DocxText: The specified color {0} is unsupported, Please specify the valid color. Ex, Red, Green", foreColor));
-
-                        string ColorShadeHex = string.Format("{0:x6}", colorShade);
-                        runProperties.AppendChild(new Shading() { Fill = ColorShadeHex.Substring(2), Val = ShadingPatternValues.Clear });
-                    }
-
-                    if (!string.IsNullOrEmpty(styleName))
-                    {
-                        Style style = part.Styles.Elements<Style>().Where(s => s.StyleId == styleName).FirstOrDefault();
-                        //if the specified style is not present in word document add it
-                        if (style == null)
-                        {
-                            using (MemoryStream memoryStream = new MemoryStream())
-                            {
-                                #region Default.dotx Template has been used to get all the paragraph styles
-                                string base64 =
-        @"UEsDBBQABgAIAAAAIQDTMB8uXgEAACAFAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbLSUy27CMBBF
-95X6D5G3VWLooqoqAos+li1S6QcYewJW/ZI9vP6+EwKoqiCRCmwiJTP33jNWxoPR2ppsCTFp70rW
-L3osAye90m5Wsq/JW/7IsoTCKWG8g5JtILHR8PZmMNkESBmpXSrZHDE8cZ7kHKxIhQ/gqFL5aAXS
-a5zxIOS3mAG/7/UeuPQOwWGOtQcbDl6gEguD2euaPjckEUxi2XPTWGeVTIRgtBRIdb506k9Kvkso
-SLntSXMd0h01MH40oa6cDtjpPuhoolaQjUXEd2Gpi698VFx5ubCkLNptjnD6qtISDvraLUQvISU6
-c2sKBBtoAiis0G7Pf5Ij4cZAujxF49sdD4gkuAbAzrkTYQXTz6tR/DLvBKkodyKmBi6PcbDuhEDa
-QGie/bM5tjZtkdQ5jj4k2uj4j7H3K1urcxo4QETd/tcdEsn67Pmgvg0UqCPZfHu/DX8AAAD//wMA
-UEsDBBQABgAIAAAAIQAekRq37wAAAE4CA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P18
-1gEAAAsDAAAQAAAAAAAAAAAAAAAAAKcCAABkb2NQcm9wcy9hcHAueG1sUEsBAi0AFAAGAAgA0WoG
-QVLD/UK6AQAAbwIAABEAAAAAAAAAAAAAAAAAqwQAAGRvY1Byb3BzL2NvcmUueG1sUEsBAi0AFAAG
-AAgAAAAhANZks1H0AAAAMQMAABwAAAAAAAAAAAAAAAAAlAYAAHdvcmQvX3JlbHMvZG9jdW1lbnQu
-eG1sLnJlbHNQSwECLQAUAAYACADRagZBeuUzdzMCAACQBQAAEQAAAAAAAAAAAAAAAADCBwAAd29y
-ZC9kb2N1bWVudC54bWxQSwECLQAUAAYACADRagZB3iZxVZoCAAAzBwAAEgAAAAAAAAAAAAAAAAAk
-CgAAd29yZC9mb250VGFibGUueG1sUEsBAi0AFAAEAAgA0WoGQYaCXUkdBAAAeQkAABEAAAAAAAAA
-AAAAAAAA7gwAAHdvcmQvc2V0dGluZ3MueG1sUEsBAi0AFAAEAAgA0WoGQSv37OFTEgAAFa0AAA8A
-AAAAAAAAAAAAAAAAOhEAAHdvcmQvc3R5bGVzLnhtbFBLAQItABQABgAIANFqBkEJ28MF3QYAAFAb
-AAAVAAAAAAAAAAAAAAAAALojAAB3b3JkL3RoZW1lL3RoZW1lMS54bWxQSwECLQAUAAYACADRagZB
-joxzCXABAAD0AQAAFAAAAAAAAAAAAAAAAADKKgAAd29yZC93ZWJTZXR0aW5ncy54bWxQSwUGAAAA
-AAsACwDBAgAAbCwAAAAA";
-                                #endregion
-
-                                char[] base64CharArray = base64.Where(c => c != '\r' && c != '\n').ToArray();
-                                byte[] byteArray = System.Convert.FromBase64CharArray(base64CharArray, 0, base64CharArray.Length);
-                                memoryStream.Write(byteArray, 0, byteArray.Length);
-
-                                using (WordprocessingDocument defaultDotx = WordprocessingDocument.Open(memoryStream, true))
-                                {
-                                    //Get the specified style from Default.dotx template for paragraph
-                                    Style templateStyle = defaultDotx.MainDocumentPart.StyleDefinitionsPart.Styles.Elements<Style>().Where(s => s.StyleId == styleName && s.Type == StyleValues.Paragraph).FirstOrDefault();
-
-                                    //Check if the style is proper style. Ex, Heading1, Heading2
-                                    if (templateStyle == null)
-                                        throw new OpenXmlPowerToolsException(String.Format("Add-DocxText: The specified style name {0} is unsupported, Please specify the valid style. Ex, Heading1, Heading2, Title", styleName));
-                                    else
-                                        part.Styles.Append((templateStyle.CloneNode(true)));
-                                }
-                            }
-                        }
-
-                        paragraph.ParagraphProperties = new ParagraphProperties(new ParagraphStyleId() { Val = styleName });
-                    }
-
-                    run.AppendChild(runProperties);
-                    run.AppendChild(new Text(strParagraph));
-
-                    if (sectionProperties != null)
-                        body.InsertBefore(paragraph, sectionProperties);
-                    else
-                        body.AppendChild(paragraph);
-                }
-                return streamDoc.GetModifiedWmlDocument();
-            }
-        }
-    }
-
-    public class HtmlConverterHelper
-    {
-        public static void ConvertToHtml(string file, string outputDirectory)
-        {
-            var fi = new FileInfo(file);
-            byte[] byteArray = File.ReadAllBytes(fi.FullName);
-            using (MemoryStream memoryStream = new MemoryStream())
-            {
-                memoryStream.Write(byteArray, 0, byteArray.Length);
-                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(memoryStream, true))
-                {
-                    var destFileName = new FileInfo(fi.Name.Replace(".docx", ".html"));
-                    if (outputDirectory != null && outputDirectory != string.Empty)
-                    {
-                        DirectoryInfo di = new DirectoryInfo(outputDirectory);
-                        if (!di.Exists)
-                        {
-                            throw new OpenXmlPowerToolsException("Output directory does not exist");
-                        }
-                        destFileName = new FileInfo(Path.Combine(di.FullName, destFileName.Name));
-                    }
-                    var imageDirectoryName = destFileName.FullName.Substring(0, destFileName.FullName.Length - 5) + "_files";
-                    int imageCounter = 0;
-                    var pageTitle = (string)wDoc.CoreFilePropertiesPart.GetXDocument().Descendants(DC.title).FirstOrDefault();
-                    if (pageTitle == null)
-                        pageTitle = fi.FullName;
-
-                    WmlToHtmlConverterSettings settings = new WmlToHtmlConverterSettings()
-                    {
-                        PageTitle = pageTitle,
-                        FabricateCssClasses = true,
-                        CssClassPrefix = "pt-",
-                        RestrictToSupportedLanguages = false,
-                        RestrictToSupportedNumberingFormats = false,
-                        ImageHandler = imageInfo =>
-                        {
-                            DirectoryInfo localDirInfo = new DirectoryInfo(imageDirectoryName);
-                            if (!localDirInfo.Exists)
-                                localDirInfo.Create();
-                            ++imageCounter;
-                            string extension = imageInfo.ContentType.Split('/')[1].ToLower();
-                            ImageFormat imageFormat = null;
-                            if (extension == "png")
-                            {
-                                // Convert png to jpeg.
-                                extension = "gif";
-                                imageFormat = ImageFormat.Gif;
-                            }
-                            else if (extension == "gif")
-                                imageFormat = ImageFormat.Gif;
-                            else if (extension == "bmp")
-                                imageFormat = ImageFormat.Bmp;
-                            else if (extension == "jpeg")
-                                imageFormat = ImageFormat.Jpeg;
-                            else if (extension == "tiff")
-                            {
-                                // Convert tiff to gif.
-                                extension = "gif";
-                                imageFormat = ImageFormat.Gif;
-                            }
-                            else if (extension == "x-wmf")
-                            {
-                                extension = "wmf";
-                                imageFormat = ImageFormat.Wmf;
-                            }
-
-                            // If the image format isn't one that we expect, ignore it,
-                            // and don't return markup for the link.
-                            if (imageFormat == null)
-                                return null;
-
-                            string imageFileName = imageDirectoryName + "/image" +
-                                imageCounter.ToString() + "." + extension;
-                            try
-                            {
-                                imageInfo.Bitmap.Save(imageFileName, imageFormat);
-                            }
-                            catch (System.Runtime.InteropServices.ExternalException)
-                            {
-                                return null;
-                            }
-                            XElement img = new XElement(Xhtml.img,
-                                new XAttribute(NoNamespace.src, imageFileName),
-                                imageInfo.ImgStyleAttribute,
-                                imageInfo.AltText != null ?
-                                    new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
-                            return img;
-                        }
-                    };
-                    XElement html = WmlToHtmlConverter.ConvertToHtml(wDoc, settings);
-
-                    // Note: the xhtml returned by ConvertToHtmlTransform contains objects of type
-                    // XEntity.  PtOpenXmlUtil.cs define the XEntity class.  See
-                    // http://blogs.msdn.com/ericwhite/archive/2010/01/21/writing-entity-references-using-linq-to-xml.aspx
-                    // for detailed explanation.
-                    //
-                    // If you further transform the XML tree returned by ConvertToHtmlTransform, you
-                    // must do it correctly, or entities will not be serialized properly.
-
-                    var htmlString = html.ToString(SaveOptions.DisableFormatting);
-                    File.WriteAllText(destFileName.FullName, htmlString, Encoding.UTF8);
-                }
-            }
-        }
-    }
-
-    public class ValidationHelper
-    {
-        public static bool IsValid(string fileName, string officeVersion)
-        {
-#if !NET35
-            FileFormatVersions fileFormatVersion = FileFormatVersions.Office2013;
-#else
-            FileFormatVersions fileFormatVersion = FileFormatVersions.Office2010;
-#endif
-            try
-            {
-                fileFormatVersion = (FileFormatVersions)Enum.Parse(fileFormatVersion.GetType(), officeVersion);
-            }
-            catch (Exception)
-            {
-#if !NET35
-                fileFormatVersion = FileFormatVersions.Office2013;
-#else
-                fileFormatVersion = FileFormatVersions.Office2010;
-#endif
-            }
-
-            FileInfo fi = new FileInfo(fileName);
-            if (Util.IsWordprocessingML(fi.Extension))
-            {
-                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(fileName, false))
-                {
-                    OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion);
-                    var errors = validator.Validate(wDoc);
-                    bool valid = errors.Count() == 0;
-                    return valid;
-                }
-            }
-            else if (Util.IsSpreadsheetML(fi.Extension))
-            {
-                using (SpreadsheetDocument sDoc = SpreadsheetDocument.Open(fileName, false))
-                {
-                    OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion);
-                    var errors = validator.Validate(sDoc);
-                    bool valid = errors.Count() == 0;
-                    return valid;
-                }
-            }
-            else if (Util.IsPresentationML(fi.Extension))
-            {
-                using (PresentationDocument pDoc = PresentationDocument.Open(fileName, false))
-                {
-                    OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion);
-                    var errors = validator.Validate(pDoc);
-                    bool valid = errors.Count() == 0;
-                    return valid;
-                }
-            }
-            return false;
-        }
-
-        public static IEnumerable<ValidationErrorInfo> GetOpenXmlValidationErrors(string fileName,
-            string officeVersion)
-        {
-#if !NET35
-            FileFormatVersions fileFormatVersion = FileFormatVersions.Office2013;
-#else
-            FileFormatVersions fileFormatVersion = FileFormatVersions.Office2010;
-#endif
-            try
-            {
-                fileFormatVersion = (FileFormatVersions)Enum.Parse(fileFormatVersion.GetType(), officeVersion);
-            }
-            catch (Exception)
-            {
-#if !NET35
-                fileFormatVersion = FileFormatVersions.Office2013;
-#else
-                fileFormatVersion = FileFormatVersions.Office2010;
-#endif
-            }
-
-            FileInfo fi = new FileInfo(fileName);
-            if (Util.IsWordprocessingML(fi.Extension))
-            {
-                WmlDocument wml = new WmlDocument(fileName);
-                using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(wml))
-                using (WordprocessingDocument wDoc = streamDoc.GetWordprocessingDocument())
-                {
-                    OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion);
-                    var errors = validator.Validate(wDoc);
-                    return errors.ToList();
-                }
-            }
-            else if (Util.IsSpreadsheetML(fi.Extension))
-            {
-                SmlDocument Sml = new SmlDocument(fileName);
-                using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(Sml))
-                using (SpreadsheetDocument wDoc = streamDoc.GetSpreadsheetDocument())
-                {
-                    OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion);
-                    var errors = validator.Validate(wDoc);
-                    return errors.ToList();
-                }
-            }
-            else if (Util.IsPresentationML(fi.Extension))
-            {
-                PmlDocument Pml = new PmlDocument(fileName);
-                using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(Pml))
-                using (PresentationDocument wDoc = streamDoc.GetPresentationDocument())
-                {
-                    OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion);
-                    var errors = validator.Validate(wDoc);
-                    return errors.ToList();
-                }
-            }
-            return Enumerable.Empty<ValidationErrorInfo>();
-        }
-    }
-
-    public class DocxMetrics
-    {
-        public string FileName;
-
-	    public int ActiveX;
-	    public int AltChunk;
-	    public int AsciiCharCount;
-	    public int AsciiRunCount;
-	    public int AverageParagraphLength;
-	    public int ComplexField;
-	    public int ContentControlCount;
-	    public XmlDocument ContentControls;
-	    public int CSCharCount;
-	    public int CSRunCount;
-	    public bool DocumentProtection;
-	    public int EastAsiaCharCount;
-	    public int EastAsiaRunCount;
-	    public int ElementCount;
-	    public bool EmbeddedXlsx;
-	    public int HAnsiCharCount;
-	    public int HAnsiRunCount;
-	    public int Hyperlink;
-	    public bool InvalidSaveThroughXslt;
-	    public string Languages;
-	    public int LegacyFrame;
-	    public int MultiFontRun;
-	    public string NumberingFormatList;
-	    public int ReferenceToNullImage;
-	    public bool RevisionTracking;
-	    public int RunCount;
-	    public int SimpleField;
-	    public XmlDocument StyleHierarchy;
-	    public int SubDocument;
-	    public int Table;
-	    public int TextBox;
-	    public bool TrackRevisionsEnabled;
-	    public bool Valid;
-        public int ZeroLengthText;
-    }
-
-    public static class GetMetricsHelper
-    {
-        public static DocxMetrics GetDocxMetrics(string fileName)
-        {
-            WmlDocument wmlDoc = new WmlDocument(fileName);
-            MetricsGetterSettings settings = new MetricsGetterSettings();
-            settings.IncludeTextInContentControls = false;
-            settings.IncludeXlsxTableCellData = false;
-            var metricsXml = MetricsGetter.GetDocxMetrics(wmlDoc, settings);
-            DocxMetrics metrics = new DocxMetrics();
-            metrics.FileName = wmlDoc.FileName;
-
-            metrics.StyleHierarchy         = GetXmlDocumentForMetrics(metricsXml, H.StyleHierarchy);
-            metrics.ContentControls        = GetXmlDocumentForMetrics(metricsXml, H.Parts);
-            metrics.TextBox                = GetIntForMetrics(metricsXml, H.TextBox);
-            metrics.ContentControlCount    = GetIntForMetrics(metricsXml, H.ContentControl);
-            metrics.ComplexField           = GetIntForMetrics(metricsXml, H.ComplexField);
-            metrics.SimpleField            = GetIntForMetrics(metricsXml, H.SimpleField);
-            metrics.AltChunk               = GetIntForMetrics(metricsXml, H.AltChunk);
-            metrics.Table                  = GetIntForMetrics(metricsXml, H.Table);
-            metrics.Hyperlink              = GetIntForMetrics(metricsXml, H.Hyperlink);
-            metrics.LegacyFrame            = GetIntForMetrics(metricsXml, H.LegacyFrame);
-            metrics.ActiveX                = GetIntForMetrics(metricsXml, H.ActiveX);
-            metrics.SubDocument            = GetIntForMetrics(metricsXml, H.SubDocument);
-            metrics.ReferenceToNullImage   = GetIntForMetrics(metricsXml, H.ReferenceToNullImage);
-            metrics.ElementCount           = GetIntForMetrics(metricsXml, H.ElementCount);
-            metrics.AverageParagraphLength = GetIntForMetrics(metricsXml, H.AverageParagraphLength);
-            metrics.RunCount               = GetIntForMetrics(metricsXml, H.RunCount);
-            metrics.ZeroLengthText         = GetIntForMetrics(metricsXml, H.ZeroLengthText);
-            metrics.MultiFontRun           = GetIntForMetrics(metricsXml, H.MultiFontRun);
-            metrics.AsciiCharCount         = GetIntForMetrics(metricsXml, H.AsciiCharCount);
-            metrics.CSCharCount            = GetIntForMetrics(metricsXml, H.CSCharCount);
-            metrics.EastAsiaCharCount      = GetIntForMetrics(metricsXml, H.EastAsiaCharCount);
-            metrics.HAnsiCharCount         = GetIntForMetrics(metricsXml, H.HAnsiCharCount);
-            metrics.AsciiRunCount          = GetIntForMetrics(metricsXml, H.AsciiRunCount);
-            metrics.CSRunCount             = GetIntForMetrics(metricsXml, H.CSRunCount);
-            metrics.EastAsiaRunCount       = GetIntForMetrics(metricsXml, H.EastAsiaRunCount);
-            metrics.HAnsiRunCount          = GetIntForMetrics(metricsXml, H.HAnsiRunCount);
-            metrics.RevisionTracking       = GetBoolForMetrics(metricsXml, H.RevisionTracking);
-            metrics.EmbeddedXlsx           = GetBoolForMetrics(metricsXml, H.EmbeddedXlsx);
-            metrics.InvalidSaveThroughXslt = GetBoolForMetrics(metricsXml, H.InvalidSaveThroughXslt);
-            metrics.TrackRevisionsEnabled  = GetBoolForMetrics(metricsXml, H.TrackRevisionsEnabled);
-            metrics.DocumentProtection     = GetBoolForMetrics(metricsXml, H.DocumentProtection);
-            metrics.Valid                  = GetBoolForMetrics(metricsXml, H.Valid);
-            metrics.Languages              = GetStringForMetrics(metricsXml, H.Languages);
-            metrics.NumberingFormatList    = GetStringForMetrics(metricsXml, H.NumberingFormatList);
-
-            return metrics;
-        }
-
-        private static string GetStringForMetrics(XElement metricsXml, XName xName)
-        {
-            var ele = metricsXml.Element(xName);
-            if (ele == null)
-                return "";
-            return (string)ele.Attribute(H.Val);
-        }
-
-        private static bool GetBoolForMetrics(XElement metricsXml, XName xName)
-        {
-            var ele = metricsXml.Element(xName);
-            if (ele == null)
-                return false;
-            return (bool)ele.Attribute(H.Val);
-        }
-
-        private static int GetIntForMetrics(XElement metricsXml, XName xName)
-        {
-            var ele = metricsXml.Element(xName);
-            if (ele == null)
-                return 0;
-            return (int)ele.Attribute(H.Val);
-        }
-
-        private static XmlDocument GetXmlDocumentForMetrics(XElement metricsXml, XName xName)
-        {
-            var ele = metricsXml.Element(xName);
-            if (ele == null)
-                return null;
-            return (new XDocument(metricsXml.Element(xName))).GetXmlDocument();
-        }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 2109
TEAMModelOS.SDK/Module/OpenXmlTool/PegBase.cs


+ 0 - 62
TEAMModelOS.SDK/Module/OpenXmlTool/PowerToolsBlock.cs

@@ -1,62 +0,0 @@
-// 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 DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    /// <summary>
-    /// Provides an elegant way of wrapping a set of invocations of the PowerTools in a using
-    /// statement that demarcates those invokations as one "block" before and after which the
-    /// strongly typed classes provided by the Open XML SDK can be used safely.
-    /// </summary>
-    /// <remarks>
-    /// <para>
-    /// This class lends itself to scenarios where the PowerTools and Linq-to-XML are used as
-    /// a secondary API for working with Open XML elements, next to the strongly typed classes
-    /// provided by the Open XML SDK. In these scenarios, the class would be
-    /// used as follows:
-    /// </para>
-    /// <code>
-    ///     [Your code using the strongly typed classes]
-    /// 
-    ///     using (new PowerToolsBlock(wordprocessingDocument))
-    ///     {
-    ///         [Your code using the PowerTools]
-    ///     }
-    /// 
-    ///    [Your code using the strongly typed classes]
-    /// </code>
-    /// <para>
-    /// Upon creation, instances of this class will invoke the
-    /// <see cref="PowerToolsBlockExtensions.BeginPowerToolsBlock"/> method on the package
-    /// to begin the transaction.  Upon disposal, instances of this class will call the
-    /// <see cref="PowerToolsBlockExtensions.EndPowerToolsBlock"/> method on the package
-    /// to end the transaction.
-    /// </para>
-    /// </remarks>
-    /// <seealso cref="StronglyTypedBlock" />
-    /// <seealso cref="PowerToolsBlockExtensions.BeginPowerToolsBlock"/>
-    /// <seealso cref="PowerToolsBlockExtensions.EndPowerToolsBlock"/>
-    public class PowerToolsBlock : IDisposable
-    {
-        private OpenXmlPackage _package;
-
-        public PowerToolsBlock(OpenXmlPackage package)
-        {
-            if (package == null) throw new ArgumentNullException("package");
-
-            _package = package;
-            _package.BeginPowerToolsBlock();
-        }
-
-        public void Dispose()
-        {
-            if (_package == null) return;
-
-            _package.EndPowerToolsBlock();
-            _package = null;
-        }
-    }
-}

+ 0 - 70
TEAMModelOS.SDK/Module/OpenXmlTool/PowerToolsBlockExtensions.cs

@@ -1,70 +0,0 @@
-// 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.Linq;
-using System.Xml;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public static class PowerToolsBlockExtensions
-    {
-        /// <summary>
-        /// Begins a PowerTools Block by (1) removing annotations and, unless the package was
-        /// opened in read-only mode, (2) saving the package.
-        /// </summary>
-        /// <remarks>
-        /// Removes <see cref="XDocument" /> and <see cref="XmlNamespaceManager" /> instances
-        /// added by <see cref="PtOpenXmlExtensions.GetXDocument(OpenXmlPart)" />,
-        /// <see cref="PtOpenXmlExtensions.GetXDocument(OpenXmlPart, out XmlNamespaceManager)" />,
-        /// <see cref="PtOpenXmlExtensions.PutXDocument(OpenXmlPart)" />,
-        /// <see cref="PtOpenXmlExtensions.PutXDocument(OpenXmlPart, XDocument)" />, and
-        /// <see cref="PtOpenXmlExtensions.PutXDocumentWithFormatting(OpenXmlPart)" />.
-        /// methods.
-        /// </remarks>
-        /// <param name="package">
-        /// A <see cref="WordprocessingDocument" />, <see cref="SpreadsheetDocument" />,
-        /// or <see cref="PresentationDocument" />.
-        /// </param>
-        public static void BeginPowerToolsBlock(this OpenXmlPackage package)
-        {
-            if (package == null) throw new ArgumentNullException("package");
-
-            package.RemovePowerToolsAnnotations();
-            package.Save();
-        }
-
-        /// <summary>
-        /// Ends a PowerTools Block by reloading the root elements of all package parts
-        /// that were changed by the PowerTools. A part is deemed changed by the PowerTools
-        /// if it has an annotation of type <see cref="XDocument" />.
-        /// </summary>
-        /// <param name="package">
-        /// A <see cref="WordprocessingDocument" />, <see cref="SpreadsheetDocument" />,
-        /// or <see cref="PresentationDocument" />.
-        /// </param>
-        public static void EndPowerToolsBlock(this OpenXmlPackage package)
-        {
-            if (package == null) throw new ArgumentNullException("package");
-
-            foreach (OpenXmlPart part in package.GetAllParts())
-            {
-                if (part.Annotations<XDocument>().Any() && part.RootElement != null)
-                    part.RootElement.Reload();
-            }
-        }
-
-        private static void RemovePowerToolsAnnotations(this OpenXmlPackage package)
-        {
-            if (package == null) throw new ArgumentNullException("package");
-
-            foreach (OpenXmlPart part in package.GetAllParts())
-            {
-                part.RemoveAnnotations<XDocument>();
-                part.RemoveAnnotations<XmlNamespaceManager>();
-            }
-        }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 1825
TEAMModelOS.SDK/Module/OpenXmlTool/PresentationBuilder.cs


+ 0 - 6
TEAMModelOS.SDK/Module/OpenXmlTool/Properties/AssemblyInfo.cs

@@ -1,6 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-using System.Runtime.CompilerServices;
-
-[assembly: InternalsVisibleTo("OpenXmlPowerTools.Tests")]

+ 0 - 757
TEAMModelOS.SDK/Module/OpenXmlTool/PtOpenXmlDocument.cs

@@ -1,757 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-/*
-Here is modification of a WmlDocument:
-    public static WmlDocument SimplifyMarkup(WmlDocument doc, SimplifyMarkupSettings settings)
-    {
-        using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
-        {
-            using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
-            {
-                SimplifyMarkup(document, settings);
-            }
-            return streamDoc.GetModifiedWmlDocument();
-        }
-    }
-
-Here is read-only of a WmlDocument:
-
-    public static string GetBackgroundColor(WmlDocument doc)
-    {
-        using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
-        using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
-        {
-            XDocument mainDocument = document.MainDocumentPart.GetXDocument();
-            XElement backgroundElement = mainDocument.Descendants(W.background).FirstOrDefault();
-            return (backgroundElement == null) ? string.Empty : backgroundElement.Attribute(W.color).Value;
-        }
-    }
-
-Here is creating a new WmlDocument:
-
-    private OpenXmlPowerToolsDocument CreateSplitDocument(WordprocessingDocument source, List<XElement> contents, string newFileName)
-    {
-        using (OpenXmlMemoryStreamDocument streamDoc = OpenXmlMemoryStreamDocument.CreateWordprocessingDocument())
-        {
-            using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
-            {
-                DocumentBuilder.FixRanges(source.MainDocumentPart.GetXDocument(), contents);
-                PowerToolsExtensions.SetContent(document, contents);
-            }
-            OpenXmlPowerToolsDocument newDoc = streamDoc.GetModifiedDocument();
-            newDoc.FileName = newFileName;
-            return newDoc;
-        }
-    }
-*/
-
-using System;
-using System.IO;
-using System.Linq;
-using System.Xml.Linq;
-using System.IO.Packaging;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public class PowerToolsDocumentException : Exception
-    {
-        public PowerToolsDocumentException(string message) : base(message) { }
-    }
-    public class PowerToolsInvalidDataException : Exception
-    {
-        public PowerToolsInvalidDataException(string message) : base(message) { }
-    }
-
-    public class OpenXmlPowerToolsDocument
-    {
-        public string FileName { get; set; }
-        public byte[] DocumentByteArray { get; set; }
-
-        public static OpenXmlPowerToolsDocument FromFileName(string fileName)
-        {
-            byte[] bytes = File.ReadAllBytes(fileName);
-            Type type;
-            try
-            {
-                type = GetDocumentType(bytes);
-            }
-            catch (FileFormatException)
-            {
-                throw new PowerToolsDocumentException("Not an Open XML document.");
-            }
-            if (type == typeof(WordprocessingDocument))
-                return new WmlDocument(fileName, bytes);
-            if (type == typeof(SpreadsheetDocument))
-                return new SmlDocument(fileName, bytes);
-            if (type == typeof(PresentationDocument))
-                return new PmlDocument(fileName, bytes);
-            if (type == typeof(Package))
-            {
-                OpenXmlPowerToolsDocument pkg = new OpenXmlPowerToolsDocument(bytes);
-                pkg.FileName = fileName;
-                return pkg;
-            }
-            throw new PowerToolsDocumentException("Not an Open XML document.");
-        }
-
-        public static OpenXmlPowerToolsDocument FromDocument(OpenXmlPowerToolsDocument doc)
-        {
-            Type type = doc.GetDocumentType();
-            if (type == typeof(WordprocessingDocument))
-                return new WmlDocument(doc);
-            if (type == typeof(SpreadsheetDocument))
-                return new SmlDocument(doc);
-            if (type == typeof(PresentationDocument))
-                return new PmlDocument(doc);
-            return null;    // This should not be possible from a valid OpenXmlPowerToolsDocument object
-        }
-
-        public OpenXmlPowerToolsDocument(OpenXmlPowerToolsDocument original)
-        {
-            DocumentByteArray = new byte[original.DocumentByteArray.Length];
-            Array.Copy(original.DocumentByteArray, DocumentByteArray, original.DocumentByteArray.Length);
-            FileName = original.FileName;
-        }
-
-        public OpenXmlPowerToolsDocument(OpenXmlPowerToolsDocument original, bool convertToTransitional)
-        {
-            if (convertToTransitional)
-            {
-                ConvertToTransitional(original.FileName, original.DocumentByteArray);
-            }
-            else
-            {
-                DocumentByteArray = new byte[original.DocumentByteArray.Length];
-                Array.Copy(original.DocumentByteArray, DocumentByteArray, original.DocumentByteArray.Length);
-                FileName = original.FileName;
-            }
-        }
-
-        public OpenXmlPowerToolsDocument(string fileName)
-        {
-            this.FileName = fileName;
-            DocumentByteArray = File.ReadAllBytes(fileName);
-        }
-
-        public OpenXmlPowerToolsDocument(string fileName, bool convertToTransitional)
-        {
-            this.FileName = fileName;
-
-            if (convertToTransitional)
-            {
-                var tempByteArray = File.ReadAllBytes(fileName);
-                ConvertToTransitional(fileName, tempByteArray);
-            }
-            else
-            {
-                this.FileName = fileName;
-                DocumentByteArray = File.ReadAllBytes(fileName);
-            }
-        }
-
-        private void ConvertToTransitional(string fileName, byte[] tempByteArray)
-        {
-            Type type;
-            try
-            {
-                type = GetDocumentType(tempByteArray);
-            }
-            catch (FileFormatException)
-            {
-                throw new PowerToolsDocumentException("Not an Open XML document.");
-            }
-
-            using (MemoryStream ms = new MemoryStream())
-            {
-                ms.Write(tempByteArray, 0, tempByteArray.Length);
-                if (type == typeof(WordprocessingDocument))
-                {
-                    using (WordprocessingDocument sDoc = WordprocessingDocument.Open(ms, true))
-                    {
-                        // following code forces the SDK to serialize
-                        foreach (var part in sDoc.Parts)
-                        {
-                            try
-                            {
-                                var z = part.OpenXmlPart.RootElement;
-                            }
-                            catch (Exception)
-                            {
-                                continue;
-                            }
-                        }
-                    }
-                }
-                else if (type == typeof(SpreadsheetDocument))
-                {
-                    using (SpreadsheetDocument sDoc = SpreadsheetDocument.Open(ms, true))
-                    {
-                        // following code forces the SDK to serialize
-                        foreach (var part in sDoc.Parts)
-                        {
-                            try
-                            {
-                                var z = part.OpenXmlPart.RootElement;
-                            }
-                            catch (Exception)
-                            {
-                                continue;
-                            }
-                        }
-                    }
-                }
-                else if (type == typeof(PresentationDocument))
-                {
-                    using (PresentationDocument sDoc = PresentationDocument.Open(ms, true))
-                    {
-                        // following code forces the SDK to serialize
-                        foreach (var part in sDoc.Parts)
-                        {
-                            try
-                            {
-                                var z = part.OpenXmlPart.RootElement;
-                            }
-                            catch (Exception)
-                            {
-                                continue;
-                            }
-                        }
-                    }
-                }
-                this.FileName = fileName;
-                DocumentByteArray = ms.ToArray();
-            }
-        }
-
-        public OpenXmlPowerToolsDocument(byte[] byteArray)
-        {
-            DocumentByteArray = new byte[byteArray.Length];
-            Array.Copy(byteArray, DocumentByteArray, byteArray.Length);
-            this.FileName = null;
-        }
-
-        public OpenXmlPowerToolsDocument(byte[] byteArray, bool convertToTransitional)
-        {
-            if (convertToTransitional)
-            {
-                ConvertToTransitional(null, byteArray);
-            }
-            else
-            {
-                DocumentByteArray = new byte[byteArray.Length];
-                Array.Copy(byteArray, DocumentByteArray, byteArray.Length);
-                this.FileName = null;
-            }
-        }
-
-        public OpenXmlPowerToolsDocument(string fileName, MemoryStream memStream)
-        {
-            FileName = fileName;
-            DocumentByteArray = new byte[memStream.Length];
-            Array.Copy(memStream.GetBuffer(), DocumentByteArray, memStream.Length);
-        }
-
-        public OpenXmlPowerToolsDocument(string fileName, MemoryStream memStream, bool convertToTransitional)
-        {
-            if (convertToTransitional)
-            {
-                ConvertToTransitional(fileName, memStream.ToArray());
-            }
-            else
-            {
-                FileName = fileName;
-                DocumentByteArray = new byte[memStream.Length];
-                Array.Copy(memStream.GetBuffer(), DocumentByteArray, memStream.Length);
-            }
-        }
-
-        public string GetName()
-        {
-            if (FileName == null)
-                return "Unnamed Document";
-            FileInfo file = new FileInfo(FileName);
-            return file.Name;
-        }
-
-        public void SaveAs(string fileName)
-        {
-            File.WriteAllBytes(fileName, DocumentByteArray);
-        }
-
-        public void Save()
-        {
-            if (this.FileName == null)
-                throw new InvalidOperationException("Attempting to Save a document that has no file name.  Use SaveAs instead.");
-            File.WriteAllBytes(this.FileName, DocumentByteArray);
-        }
-
-        public void WriteByteArray(Stream stream)
-        {
-            stream.Write(DocumentByteArray, 0, DocumentByteArray.Length);
-        }
-
-        public Type GetDocumentType()
-        {
-            return GetDocumentType(DocumentByteArray);
-        }
-
-        private static Type GetDocumentType(byte[] bytes)
-        {
-            using (MemoryStream stream = new MemoryStream())
-            {
-                stream.Write(bytes, 0, bytes.Length);
-                using (Package package = Package.Open(stream, FileMode.Open))
-                {
-                    PackageRelationship relationship = package.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument").FirstOrDefault();
-                    if (relationship == null)
-                        relationship = package.GetRelationshipsByType("http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument").FirstOrDefault();
-                    if (relationship != null)
-                    {
-                        PackagePart part = package.GetPart(PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri));
-                        switch (part.ContentType)
-                        {
-                            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml":
-                            case "application/vnd.ms-word.document.macroEnabled.main+xml":
-                            case "application/vnd.ms-word.template.macroEnabledTemplate.main+xml":
-                            case "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml":
-                                return typeof(WordprocessingDocument);
-                            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml":
-                            case "application/vnd.ms-excel.sheet.macroEnabled.main+xml":
-                            case "application/vnd.ms-excel.template.macroEnabled.main+xml":
-                            case "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":
-                                return typeof(SpreadsheetDocument);
-                            case "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml":
-                            case "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml":
-                            case "application/vnd.ms-powerpoint.template.macroEnabled.main+xml":
-                            case "application/vnd.ms-powerpoint.addin.macroEnabled.main+xml":
-                            case "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml":
-                            case "application/vnd.ms-powerpoint.presentation.macroEnabled.main+xml":
-                                return typeof(PresentationDocument);
-                        }
-                        return typeof(Package);
-                    }
-                    return null;
-                }
-            }
-        }
-
-        public static void SavePartAs(OpenXmlPart part, string filePath)
-        {
-            Stream partStream = part.GetStream(FileMode.Open, FileAccess.Read);
-            byte[] partContent = new byte[partStream.Length];
-            partStream.Read(partContent, 0, (int)partStream.Length);
-
-            File.WriteAllBytes(filePath, partContent);
-        }
-    }
-
-    public partial class WmlDocument : OpenXmlPowerToolsDocument
-    {
-        public WmlDocument(OpenXmlPowerToolsDocument original)
-            : base(original)
-        {
-            if (GetDocumentType() != typeof(WordprocessingDocument))
-                throw new PowerToolsDocumentException("Not a Wordprocessing document.");
-        }
-
-        public WmlDocument(OpenXmlPowerToolsDocument original, bool convertToTransitional)
-            : base(original, convertToTransitional)
-        {
-            if (GetDocumentType() != typeof(WordprocessingDocument))
-                throw new PowerToolsDocumentException("Not a Wordprocessing document.");
-        }
-
-        public WmlDocument(string fileName)
-            : base(fileName)
-        {
-            if (GetDocumentType() != typeof(WordprocessingDocument))
-                throw new PowerToolsDocumentException("Not a Wordprocessing document.");
-        }
-
-        public WmlDocument(string fileName, bool convertToTransitional)
-            : base(fileName, convertToTransitional)
-        {
-            if (GetDocumentType() != typeof(WordprocessingDocument))
-                throw new PowerToolsDocumentException("Not a Wordprocessing document.");
-        }
-
-        public WmlDocument(string fileName, byte[] byteArray)
-            : base(byteArray)
-        {
-            FileName = fileName;
-            if (GetDocumentType() != typeof(WordprocessingDocument))
-                throw new PowerToolsDocumentException("Not a Wordprocessing document.");
-        }
-
-        public WmlDocument(string fileName, byte[] byteArray, bool convertToTransitional)
-            : base(byteArray, convertToTransitional)
-        {
-            FileName = fileName;
-            if (GetDocumentType() != typeof(WordprocessingDocument))
-                throw new PowerToolsDocumentException("Not a Wordprocessing document.");
-        }
-
-        public WmlDocument(string fileName, MemoryStream memStream)
-            : base(fileName, memStream)
-        {
-        }
-
-        public WmlDocument(string fileName, MemoryStream memStream, bool convertToTransitional)
-            : base(fileName, memStream, convertToTransitional)
-        {
-        }
-    }
-
-    public partial class SmlDocument : OpenXmlPowerToolsDocument
-    {
-        public SmlDocument(OpenXmlPowerToolsDocument original)
-            : base(original)
-        {
-            if (GetDocumentType() != typeof(SpreadsheetDocument))
-                throw new PowerToolsDocumentException("Not a Spreadsheet document.");
-        }
-
-        public SmlDocument(OpenXmlPowerToolsDocument original, bool convertToTransitional)
-            : base(original, convertToTransitional)
-        {
-            if (GetDocumentType() != typeof(SpreadsheetDocument))
-                throw new PowerToolsDocumentException("Not a Spreadsheet document.");
-        }
-
-        public SmlDocument(string fileName)
-            : base(fileName)
-        {
-            if (GetDocumentType() != typeof(SpreadsheetDocument))
-                throw new PowerToolsDocumentException("Not a Spreadsheet document.");
-        }
-
-        public SmlDocument(string fileName, bool convertToTransitional)
-            : base(fileName, convertToTransitional)
-        {
-            if (GetDocumentType() != typeof(SpreadsheetDocument))
-                throw new PowerToolsDocumentException("Not a Spreadsheet document.");
-        }
-
-        public SmlDocument(string fileName, byte[] byteArray)
-            : base(byteArray)
-        {
-            FileName = fileName;
-            if (GetDocumentType() != typeof(SpreadsheetDocument))
-                throw new PowerToolsDocumentException("Not a Spreadsheet document.");
-        }
-
-        public SmlDocument(string fileName, byte[] byteArray, bool convertToTransitional)
-            : base(byteArray, convertToTransitional)
-        {
-            FileName = fileName;
-            if (GetDocumentType() != typeof(SpreadsheetDocument))
-                throw new PowerToolsDocumentException("Not a Spreadsheet document.");
-        }
-
-        public SmlDocument(string fileName, MemoryStream memStream)
-            : base(fileName, memStream)
-        {
-        }
-
-        public SmlDocument(string fileName, MemoryStream memStream, bool convertToTransitional)
-            : base(fileName, memStream, convertToTransitional)
-        {
-        }
-    }
-
-    public partial class PmlDocument : OpenXmlPowerToolsDocument
-    {
-        public PmlDocument(OpenXmlPowerToolsDocument original)
-            : base(original)
-        {
-            if (GetDocumentType() != typeof(PresentationDocument))
-                throw new PowerToolsDocumentException("Not a Presentation document.");
-        }
-
-        public PmlDocument(OpenXmlPowerToolsDocument original, bool convertToTransitional)
-            : base(original, convertToTransitional)
-        {
-            if (GetDocumentType() != typeof(PresentationDocument))
-                throw new PowerToolsDocumentException("Not a Presentation document.");
-        }
-
-        public PmlDocument(string fileName)
-            : base(fileName)
-        {
-            if (GetDocumentType() != typeof(PresentationDocument))
-                throw new PowerToolsDocumentException("Not a Presentation document.");
-        }
-
-        public PmlDocument(string fileName, bool convertToTransitional)
-            : base(fileName, convertToTransitional)
-        {
-            if (GetDocumentType() != typeof(PresentationDocument))
-                throw new PowerToolsDocumentException("Not a Presentation document.");
-        }
-
-        public PmlDocument(string fileName, byte[] byteArray)
-            : base(byteArray)
-        {
-            FileName = fileName;
-            if (GetDocumentType() != typeof(PresentationDocument))
-                throw new PowerToolsDocumentException("Not a Presentation document.");
-        }
-
-        public PmlDocument(string fileName, byte[] byteArray, bool convertToTransitional)
-            : base(byteArray, convertToTransitional)
-        {
-            FileName = fileName;
-            if (GetDocumentType() != typeof(PresentationDocument))
-                throw new PowerToolsDocumentException("Not a Presentation document.");
-        }
-
-        public PmlDocument(string fileName, MemoryStream memStream)
-            : base(fileName, memStream)
-        {
-        }
-
-        public PmlDocument(string fileName, MemoryStream memStream, bool convertToTransitional)
-            : base(fileName, memStream, convertToTransitional)
-        {
-        }
-    }
-
-    public class OpenXmlMemoryStreamDocument : IDisposable
-    {
-        private OpenXmlPowerToolsDocument Document;
-        private MemoryStream DocMemoryStream;
-        private Package DocPackage;
-
-        public OpenXmlMemoryStreamDocument(OpenXmlPowerToolsDocument doc)
-        {
-            Document = doc;
-            DocMemoryStream = new MemoryStream();
-            DocMemoryStream.Write(doc.DocumentByteArray, 0, doc.DocumentByteArray.Length);
-            try
-            {
-                DocPackage = Package.Open(DocMemoryStream, FileMode.Open);
-            }
-            catch (Exception e)
-            {
-                throw new PowerToolsDocumentException(e.Message);
-            }
-        }
-
-        internal OpenXmlMemoryStreamDocument(MemoryStream stream)
-        {
-            DocMemoryStream = stream;
-            try
-            {
-                DocPackage = Package.Open(DocMemoryStream, FileMode.Open);
-            }
-            catch (Exception e)
-            {
-                throw new PowerToolsDocumentException(e.Message);
-            }
-        }
-
-        public static OpenXmlMemoryStreamDocument CreateWordprocessingDocument()
-        {
-            MemoryStream stream = new MemoryStream();
-            using (WordprocessingDocument doc = WordprocessingDocument.Create(stream, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
-            {
-                doc.AddMainDocumentPart();
-                doc.MainDocumentPart.PutXDocument(new XDocument(
-                    new XElement(W.document,
-                        new XAttribute(XNamespace.Xmlns + "w", W.w),
-                        new XAttribute(XNamespace.Xmlns + "r", R.r),
-                        new XElement(W.body))));
-                doc.Close();
-                return new OpenXmlMemoryStreamDocument(stream);
-            }
-        }
-        public static OpenXmlMemoryStreamDocument CreateSpreadsheetDocument()
-        {
-            MemoryStream stream = new MemoryStream();
-            using (SpreadsheetDocument doc = SpreadsheetDocument.Create(stream, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
-            {
-                doc.AddWorkbookPart();
-                XNamespace ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
-                XNamespace relationshipsns = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
-                doc.WorkbookPart.PutXDocument(new XDocument(
-                    new XElement(ns + "workbook",
-                        new XAttribute("xmlns", ns),
-                        new XAttribute(XNamespace.Xmlns + "r", relationshipsns),
-                        new XElement(ns + "sheets"))));
-                doc.Close();
-                return new OpenXmlMemoryStreamDocument(stream);
-            }
-        }
-        public static OpenXmlMemoryStreamDocument CreatePresentationDocument()
-        {
-            MemoryStream stream = new MemoryStream();
-            using (PresentationDocument doc = PresentationDocument.Create(stream, DocumentFormat.OpenXml.PresentationDocumentType.Presentation))
-            {
-                doc.AddPresentationPart();
-                XNamespace ns = "http://schemas.openxmlformats.org/presentationml/2006/main";
-                XNamespace relationshipsns = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
-                XNamespace drawingns = "http://schemas.openxmlformats.org/drawingml/2006/main";
-                doc.PresentationPart.PutXDocument(new XDocument(
-                    new XElement(ns + "presentation",
-                        new XAttribute(XNamespace.Xmlns + "a", drawingns),
-                        new XAttribute(XNamespace.Xmlns + "r", relationshipsns),
-                        new XAttribute(XNamespace.Xmlns + "p", ns),
-                        new XElement(ns + "sldMasterIdLst"),
-                        new XElement(ns + "sldIdLst"),
-                        new XElement(ns + "notesSz", new XAttribute("cx", "6858000"), new XAttribute("cy", "9144000")))));
-                doc.Close();
-                return new OpenXmlMemoryStreamDocument(stream);
-            }
-        }
-
-        public static OpenXmlMemoryStreamDocument CreatePackage()
-        {
-            MemoryStream stream = new MemoryStream();
-            Package package = Package.Open(stream, FileMode.Create);
-            package.Close();
-            return new OpenXmlMemoryStreamDocument(stream);
-        }
-
-        public Package GetPackage()
-        {
-            return DocPackage;
-        }
-
-        public WordprocessingDocument GetWordprocessingDocument()
-        {
-            try
-            {
-                if (GetDocumentType() != typeof(WordprocessingDocument))
-                    throw new PowerToolsDocumentException("Not a Wordprocessing document.");
-                return WordprocessingDocument.Open(DocPackage);
-            }
-            catch (Exception e)
-            {
-                throw new PowerToolsDocumentException(e.Message);
-            }
-        }
-        public SpreadsheetDocument GetSpreadsheetDocument()
-        {
-            try
-            {
-                if (GetDocumentType() != typeof(SpreadsheetDocument))
-                    throw new PowerToolsDocumentException("Not a Spreadsheet document.");
-                return SpreadsheetDocument.Open(DocPackage);
-            }
-            catch (Exception e)
-            {
-                throw new PowerToolsDocumentException(e.Message);
-            }
-        }
-
-        public PresentationDocument GetPresentationDocument()
-        {
-            try
-            {
-                if (GetDocumentType() != typeof(PresentationDocument))
-                    throw new PowerToolsDocumentException("Not a Presentation document.");
-                return PresentationDocument.Open(DocPackage);
-            }
-            catch (Exception e)
-            {
-                throw new PowerToolsDocumentException(e.Message);
-            }
-        }
-
-        public Type GetDocumentType()
-        {
-            PackageRelationship relationship = DocPackage.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument").FirstOrDefault();
-            if (relationship == null)
-                relationship = DocPackage.GetRelationshipsByType("http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument").FirstOrDefault();
-            if (relationship == null)
-                throw new PowerToolsDocumentException("Not an Open XML Document.");
-            PackagePart part = DocPackage.GetPart(PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri));
-            switch (part.ContentType)
-            {
-                case "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml":
-                case "application/vnd.ms-word.document.macroEnabled.main+xml":
-                case "application/vnd.ms-word.template.macroEnabledTemplate.main+xml":
-                case "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml":
-                    return typeof(WordprocessingDocument);
-                case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml":
-                case "application/vnd.ms-excel.sheet.macroEnabled.main+xml":
-                case "application/vnd.ms-excel.template.macroEnabled.main+xml":
-                case "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":
-                    return typeof(SpreadsheetDocument);
-                case "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml":
-                case "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml":
-                case "application/vnd.ms-powerpoint.template.macroEnabled.main+xml":
-                case "application/vnd.ms-powerpoint.addin.macroEnabled.main+xml":
-                case "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml":
-                case "application/vnd.ms-powerpoint.presentation.macroEnabled.main+xml":
-                    return typeof(PresentationDocument);
-            }
-            return null;
-        }
-
-        public OpenXmlPowerToolsDocument GetModifiedDocument()
-        {
-            DocPackage.Close();
-            DocPackage = null;
-            return new OpenXmlPowerToolsDocument((Document == null) ? null : Document.FileName, DocMemoryStream);
-        }
-
-        public WmlDocument GetModifiedWmlDocument()
-        {
-            DocPackage.Close();
-            DocPackage = null;
-            return new WmlDocument((Document == null) ? null : Document.FileName, DocMemoryStream);
-        }
-
-        public SmlDocument GetModifiedSmlDocument()
-        {
-            DocPackage.Close();
-            DocPackage = null;
-            return new SmlDocument((Document == null) ? null : Document.FileName, DocMemoryStream);
-        }
-
-        public PmlDocument GetModifiedPmlDocument()
-        {
-            DocPackage.Close();
-            DocPackage = null;
-            return new PmlDocument((Document == null) ? null : Document.FileName, DocMemoryStream);
-        }
-
-        public void Close()
-        {
-            Dispose(true);
-        }
-
-        public void Dispose()
-        {
-            Dispose(true);
-        }
-
-        ~OpenXmlMemoryStreamDocument()
-        {
-            Dispose(false);
-        }
-
-        private void Dispose(Boolean disposing)
-        {
-            if (disposing)
-            {
-                if (DocPackage != null)
-                {
-                    DocPackage.Close();
-                }
-                if (DocMemoryStream != null)
-                {
-                    DocMemoryStream.Dispose();
-                }
-            }
-            if (DocPackage == null && DocMemoryStream == null)
-                return;
-            DocPackage = null;
-            DocMemoryStream = null;
-            GC.SuppressFinalize(this);
-        }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 5957
TEAMModelOS.SDK/Module/OpenXmlTool/PtOpenXmlUtil.cs


文件差異過大導致無法顯示
+ 0 - 1248
TEAMModelOS.SDK/Module/OpenXmlTool/PtUtil.cs


+ 0 - 639
TEAMModelOS.SDK/Module/OpenXmlTool/ReferenceAdder.cs

@@ -1,639 +0,0 @@
-// 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.IO;
-using System.Linq;
-using System.Xml;
-using System.Xml.Linq;
-using System.Xml.XPath;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public partial class WmlDocument : OpenXmlPowerToolsDocument
-    {
-        public WmlDocument AddToc(string xPath, string switches, string title, int? rightTabPos)
-        {
-            return (WmlDocument)ReferenceAdder.AddToc(this, xPath, switches, title, rightTabPos);
-        }
-        public WmlDocument AddTof(string xPath, string switches, int? rightTabPos)
-        {
-            return (WmlDocument)ReferenceAdder.AddTof(this, xPath, switches, rightTabPos);
-        }
-        public WmlDocument AddToa(string xPath, string switches, int? rightTabPos)
-        {
-            return (WmlDocument)ReferenceAdder.AddToa(this, xPath, switches, rightTabPos);
-        }
-    }
-
-    public class ReferenceAdder
-    {
-        public static WmlDocument AddToc(WmlDocument document, string xPath, string switches, string title, int? rightTabPos)
-        {
-            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
-            {
-                using (WordprocessingDocument doc = streamDoc.GetWordprocessingDocument())
-                {
-                    AddToc(doc, xPath, switches, title, rightTabPos);
-                }
-                return streamDoc.GetModifiedWmlDocument();
-            }
-        }
-
-        public static void AddToc(WordprocessingDocument doc, string xPath, string switches, string title, int? rightTabPos)
-        {
-            UpdateFontTablePart(doc);
-            UpdateStylesPartForToc(doc);
-            UpdateStylesWithEffectsPartForToc(doc);
-
-            if (title == null)
-                title = "Contents";
-            if (rightTabPos == null)
-                rightTabPos = 9350;
-
-            // {0} tocTitle (default = "Contents")
-            // {1} rightTabPosition (default = 9350)
-            // {2} switches
-
-            String xmlString =
-@"<w:sdt xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-  <w:sdtPr>
-    <w:docPartObj>
-      <w:docPartGallery w:val='Table of Contents'/>
-      <w:docPartUnique/>
-    </w:docPartObj>
-  </w:sdtPr>
-  <w:sdtEndPr>
-    <w:rPr>
-     <w:rFonts w:asciiTheme='minorHAnsi' w:cstheme='minorBidi' w:eastAsiaTheme='minorHAnsi' w:hAnsiTheme='minorHAnsi'/>
-     <w:color w:val='auto'/>
-     <w:sz w:val='22'/>
-     <w:szCs w:val='22'/>
-     <w:lang w:eastAsia='en-US'/>
-    </w:rPr>
-  </w:sdtEndPr>
-  <w:sdtContent>
-    <w:p>
-      <w:pPr>
-        <w:pStyle w:val='TOCHeading'/>
-      </w:pPr>
-      <w:r>
-        <w:t>{0}</w:t>
-      </w:r>
-    </w:p>
-    <w:p>
-      <w:pPr>
-        <w:pStyle w:val='TOC1'/>
-        <w:tabs>
-          <w:tab w:val='right' w:leader='dot' w:pos='{1}'/>
-        </w:tabs>
-        <w:rPr>
-          <w:noProof/>
-        </w:rPr>
-      </w:pPr>
-      <w:r>
-        <w:fldChar w:fldCharType='begin' w:dirty='true'/>
-      </w:r>
-      <w:r>
-        <w:instrText xml:space='preserve'> {2} </w:instrText>
-      </w:r>
-      <w:r>
-        <w:fldChar w:fldCharType='separate'/>
-      </w:r>
-    </w:p>
-    <w:p>
-      <w:r>
-        <w:rPr>
-          <w:b/>
-          <w:bCs/>
-          <w:noProof/>
-        </w:rPr>
-        <w:fldChar w:fldCharType='end'/>
-      </w:r>
-    </w:p>
-  </w:sdtContent>
-</w:sdt>";
-
-            XmlReader sdtReader = XmlReader.Create(new StringReader(String.Format(xmlString, title, rightTabPos, switches)));
-            XElement sdt = XElement.Load(sdtReader);
-
-            XmlNamespaceManager namespaceManager;
-            XDocument mainXDoc = doc.MainDocumentPart.GetXDocument(out namespaceManager);
-            namespaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
-            XElement addBefore = mainXDoc.XPathSelectElement(xPath, namespaceManager);
-            if (addBefore == null)
-                throw new OpenXmlPowerToolsException("XPath expression did not select an element");
-
-            addBefore.AddBeforeSelf(sdt);
-            doc.MainDocumentPart.PutXDocument();
-
-            XDocument settingsXDoc = doc.MainDocumentPart.DocumentSettingsPart.GetXDocument();
-            XElement updateFields = settingsXDoc.Descendants(W.updateFields).FirstOrDefault();
-            if (updateFields != null)
-                updateFields.Attribute(W.val).Value = "true";
-            else
-            {
-                updateFields = new XElement(W.updateFields,
-                    new XAttribute(W.val, "true"));
-                settingsXDoc.Root.Add(updateFields);
-            }
-            doc.MainDocumentPart.DocumentSettingsPart.PutXDocument();
-        }
-
-        public static WmlDocument AddTof(WmlDocument document, string xPath, string switches, int? rightTabPos)
-        {
-            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
-            {
-                using (WordprocessingDocument doc = streamDoc.GetWordprocessingDocument())
-                {
-                    AddTof(doc, xPath, switches, rightTabPos);
-                }
-                return streamDoc.GetModifiedWmlDocument();
-            }
-        }
-
-        public static void AddTof(WordprocessingDocument doc, string xPath, string switches, int? rightTabPos)
-        {
-            UpdateFontTablePart(doc);
-            UpdateStylesPartForTof(doc);
-            UpdateStylesWithEffectsPartForTof(doc);
-
-            if (rightTabPos == null)
-                rightTabPos = 9350;
-
-            // {0} rightTabPosition (default = 9350)
-            // {1} switches
-
-            string xmlString =
-@"<w:p xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-  <w:pPr>
-    <w:pStyle w:val='TableofFigures'/>
-    <w:tabs>
-      <w:tab w:val='right' w:leader='dot' w:pos='{0}'/>
-    </w:tabs>
-    <w:rPr>
-      <w:noProof/>
-    </w:rPr>
-  </w:pPr>
-  <w:r>
-    <w:fldChar w:fldCharType='begin' dirty='true'/>
-  </w:r>
-  <w:r>
-    <w:instrText xml:space='preserve'> {1} </w:instrText>
-  </w:r>
-  <w:r>
-    <w:fldChar w:fldCharType='separate'/>
-  </w:r>
-  <w:r>
-    <w:fldChar w:fldCharType='end'/>
-  </w:r>
-</w:p>";
-            XDocument mainXDoc = doc.MainDocumentPart.GetXDocument();
-
-            XmlReader paragraphReader = XmlReader.Create(new StringReader(String.Format(xmlString, rightTabPos, switches)));
-            XElement paragraph = XElement.Load(paragraphReader);
-            XmlNameTable nameTable = paragraphReader.NameTable;
-            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(nameTable);
-            namespaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
-            XElement addBefore = mainXDoc.XPathSelectElement(xPath, namespaceManager);
-            if (addBefore == null)
-                throw new OpenXmlPowerToolsException("XPath expression did not select an element");
-
-            addBefore.AddBeforeSelf(paragraph);
-            doc.MainDocumentPart.PutXDocument();
-
-            XDocument settingsXDoc = doc.MainDocumentPart.DocumentSettingsPart.GetXDocument();
-            XElement updateFields = settingsXDoc.Descendants(W.updateFields).FirstOrDefault();
-            if (updateFields != null)
-                updateFields.Attribute(W.val).Value = "true";
-            else
-            {
-                updateFields = new XElement(W.updateFields,
-                    new XAttribute(W.val, "true"));
-                settingsXDoc.Root.Add(updateFields);
-            }
-            doc.MainDocumentPart.DocumentSettingsPart.PutXDocument();
-        }
-
-        public static WmlDocument AddToa(WmlDocument document, string xPath, string switches, int? rightTabPos)
-        {
-            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
-            {
-                using (WordprocessingDocument doc = streamDoc.GetWordprocessingDocument())
-                {
-                    AddToa(doc, xPath, switches, rightTabPos);
-                }
-                return streamDoc.GetModifiedWmlDocument();
-            }
-        }
-
-        public static void AddToa(WordprocessingDocument doc, string xPath, string switches, int? rightTabPos)
-        {
-            UpdateFontTablePart(doc);
-            UpdateStylesPartForToa(doc);
-            UpdateStylesWithEffectsPartForToa(doc);
-
-            if (rightTabPos == null)
-                rightTabPos = 9350;
-
-            // {0} rightTabPosition (default = 9350)
-            // {1} switches
-
-            string xmlString =
-@"<w:p xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-  <w:pPr>
-    <w:pStyle w:val='TOAHeading'/>
-    <w:tabs>
-      <w:tab w:val='right'
-             w:leader='dot'
-             w:pos='{0}'/>
-      </w:tabs>
-    <w:rPr>
-      <w:rFonts w:asciiTheme='minorHAnsi'
-                w:eastAsiaTheme='minorEastAsia'
-                w:hAnsiTheme='minorHAnsi'
-                w:cstheme='minorBidi'/>
-      <w:b w:val='0'/>
-      <w:bCs w:val='0'/>
-      <w:noProof/>
-      <w:sz w:val='22'/>
-      <w:szCs w:val='22'/>
-    </w:rPr>
-  </w:pPr>
-  <w:r>
-    <w:fldChar w:fldCharType='begin'/>
-  </w:r>
-  <w:r>
-    <w:instrText xml:space='preserve'> {1} </w:instrText>
-  </w:r>
-  <w:r>
-    <w:fldChar w:fldCharType='separate'/>
-  </w:r>
-  <w:r>
-    <w:fldChar w:fldCharType='end'/>
-  </w:r>
-</w:p>";
-
-            XDocument mainXDoc = doc.MainDocumentPart.GetXDocument();
-
-            XmlReader paragraphReader = XmlReader.Create(new StringReader(String.Format(xmlString, rightTabPos, switches)));
-            XElement paragraph = XElement.Load(paragraphReader);
-            XmlNameTable nameTable = paragraphReader.NameTable;
-            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(nameTable);
-            namespaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
-            XElement addBefore = mainXDoc.XPathSelectElement(xPath, namespaceManager);
-            if (addBefore == null)
-                throw new OpenXmlPowerToolsException("XPath expression did not select an element");
-
-            addBefore.AddBeforeSelf(paragraph);
-            doc.MainDocumentPart.PutXDocument();
-
-            XDocument settingsXDoc = doc.MainDocumentPart.DocumentSettingsPart.GetXDocument();
-            XElement updateFields = settingsXDoc.Descendants(W.updateFields).FirstOrDefault();
-            if (updateFields != null)
-                updateFields.Attribute(W.val).Value = "true";
-            else
-            {
-                updateFields = new XElement(W.updateFields,
-                    new XAttribute(W.val, "true"));
-                settingsXDoc.Root.Add(updateFields);
-            }
-            doc.MainDocumentPart.DocumentSettingsPart.PutXDocument();
-        }
-
-        private 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();
-            partXDoc.Root.Add(newXElement);
-        }
-
-        private static void UpdateFontTablePart(WordprocessingDocument doc)
-        {
-            FontTablePart fontTablePart = doc.MainDocumentPart.FontTablePart;
-            if (fontTablePart == null)
-                throw new Exception("Todo need to insert font table part");
-            XDocument fontTableXDoc = fontTablePart.GetXDocument();
-
-            AddElementIfMissing(fontTableXDoc,
-                fontTableXDoc
-                    .Root
-                    .Elements(W.font)
-                    .Where(e => (string)e.Attribute(W.name) == "Tahoma")
-                    .FirstOrDefault(),
-                @"<w:font w:name='Tahoma' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-                     <w:panose1 w:val='020B0604030504040204'/>
-                     <w:charset w:val='00'/>
-                     <w:family w:val='swiss'/>
-                     <w:pitch w:val='variable'/>
-                     <w:sig w:usb0='E1002EFF' w:usb1='C000605B' w:usb2='00000029' w:usb3='00000000' w:csb0='000101FF' w:csb1='00000000'/>
-                   </w:font>");
-
-            fontTablePart.PutXDocument();
-        }
-
-        private static void UpdatePartForToc(OpenXmlPart part)
-        {
-            XDocument xDoc = part.GetXDocument();
-
-            AddElementIfMissing(
-                xDoc,
-                xDoc.Root.Elements(W.style)
-                    .Where(e => (string)e.Attribute(W.type) == "paragraph" && (string)e.Attribute(W.styleId) == "TOCHeading")
-                    .FirstOrDefault(),
-                @"<w:style w:type='paragraph' w:styleId='TOCHeading' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-                    <w:name w:val='TOC Heading'/>
-                    <w:basedOn w:val='Heading1'/>
-                    <w:next w:val='Normal'/>
-                    <w:uiPriority w:val='39'/>
-                    <w:semiHidden/>
-                    <w:unhideWhenUsed/>
-                    <w:qFormat/>
-                    <w:pPr>
-                      <w:outlineLvl w:val='9'/>
-                    </w:pPr>
-                    <w:rPr>
-                      <w:lang w:eastAsia='ja-JP'/>
-                    </w:rPr>
-                  </w:style>");
-
-            AddElementIfMissing(
-                xDoc,
-                xDoc.Root.Elements(W.style)
-                    .Where(e => (string)e.Attribute(W.type) == "paragraph" && (string)e.Attribute(W.styleId) == "TOC1")
-                    .FirstOrDefault(),
-                @"<w:style w:type='paragraph' w:styleId='TOC1' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-                    <w:name w:val='toc 1'/>
-                    <w:basedOn w:val='Normal'/>
-                    <w:next w:val='Normal'/>
-                    <w:autoRedefine/>
-                    <w:uiPriority w:val='39'/>
-                    <w:unhideWhenUsed/>
-                    <w:pPr>
-                      <w:spacing w:after='100'/>
-                    </w:pPr>
-                  </w:style>");
-
-            AddElementIfMissing(
-                xDoc,
-                xDoc.Root.Elements(W.style)
-                    .Where(e => (string)e.Attribute(W.type) == "paragraph" && (string)e.Attribute(W.styleId) == "TOC2")
-                    .FirstOrDefault(),
-                @"<w:style w:type='paragraph' w:styleId='TOC2' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-                    <w:name w:val='toc 2'/>
-                    <w:basedOn w:val='Normal'/>
-                    <w:next w:val='Normal'/>
-                    <w:autoRedefine/>
-                    <w:uiPriority w:val='39'/>
-                    <w:unhideWhenUsed/>
-                    <w:pPr>
-                      <w:spacing w:after='100'/>
-                      <w:ind w:left='220'/>
-                    </w:pPr>
-                  </w:style>");
-
-            AddElementIfMissing(
-                xDoc,
-                xDoc.Root.Elements(W.style)
-                    .Where(e => (string)e.Attribute(W.type) == "paragraph" && (string)e.Attribute(W.styleId) == "TOC3")
-                    .FirstOrDefault(),
-                @"<w:style w:type='paragraph' w:styleId='TOC3' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-                    <w:name w:val='toc 3'/>
-                    <w:basedOn w:val='Normal'/>
-                    <w:next w:val='Normal'/>
-                    <w:autoRedefine/>
-                    <w:uiPriority w:val='39'/>
-                    <w:unhideWhenUsed/>
-                    <w:pPr>
-                      <w:spacing w:after='100'/>
-                      <w:ind w:left='440'/>
-                    </w:pPr>
-                  </w:style>");
-
-            AddElementIfMissing(
-                xDoc,
-                xDoc.Root.Elements(W.style)
-                    .Where(e => (string)e.Attribute(W.type) == "paragraph" && (string)e.Attribute(W.styleId) == "TOC4")
-                    .FirstOrDefault(),
-                @"<w:style w:type='paragraph' w:styleId='TOC4' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-                    <w:name w:val='toc 4'/>
-                    <w:basedOn w:val='Normal'/>
-                    <w:next w:val='Normal'/>
-                    <w:autoRedefine/>
-                    <w:uiPriority w:val='39'/>
-                    <w:unhideWhenUsed/>
-                    <w:pPr>
-                      <w:spacing w:after='100'/>
-                      <w:ind w:left='660'/>
-                    </w:pPr>
-                  </w:style>");
-
-            AddElementIfMissing(
-                xDoc,
-                xDoc.Root.Elements(W.style)
-                    .Where(e => (string)e.Attribute(W.type) == "character" && (string)e.Attribute(W.styleId) == "Hyperlink")
-                    .FirstOrDefault(),
-                @"<w:style w:type='character' w:styleId='Hyperlink' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-                     <w:name w:val='Hyperlink'/>
-                     <w:basedOn w:val='DefaultParagraphFont'/>
-                     <w:uiPriority w:val='99'/>
-                     <w:unhideWhenUsed/>
-                     <w:rPr>
-                       <w:color w:val='0000FF' w:themeColor='hyperlink'/>
-                       <w:u w:val='single'/>
-                     </w:rPr>
-                   </w:style>");
-
-            AddElementIfMissing(
-                xDoc,
-                xDoc.Root.Elements(W.style)
-                    .Where(e => (string)e.Attribute(W.type) == "paragraph" && (string)e.Attribute(W.styleId) == "BalloonText")
-                    .FirstOrDefault(),
-                @"<w:style w:type='paragraph' w:styleId='BalloonText' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-                    <w:name w:val='Balloon Text'/>
-                    <w:basedOn w:val='Normal'/>
-                    <w:link w:val='BalloonTextChar'/>
-                    <w:uiPriority w:val='99'/>
-                    <w:semiHidden/>
-                    <w:unhideWhenUsed/>
-                    <w:pPr>
-                      <w:spacing w:after='0' w:line='240' w:lineRule='auto'/>
-                    </w:pPr>
-                    <w:rPr>
-                      <w:rFonts w:ascii='Tahoma' w:hAnsi='Tahoma' w:cs='Tahoma'/>
-                      <w:sz w:val='16'/>
-                      <w:szCs w:val='16'/>
-                    </w:rPr>
-                  </w:style>");
-
-            AddElementIfMissing(
-                xDoc,
-                xDoc.Root.Elements(W.style)
-                    .Where(e => (string)e.Attribute(W.type) == "character" &&
-                        (bool?)e.Attribute(W.customStyle) == true && (string)e.Attribute(W.styleId) == "BalloonTextChar")
-                    .FirstOrDefault(),
-                @"<w:style w:type='character' w:customStyle='1' w:styleId='BalloonTextChar' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-                    <w:name w:val='Balloon Text Char'/>
-                    <w:basedOn w:val='DefaultParagraphFont'/>
-                    <w:link w:val='BalloonText'/>
-                    <w:uiPriority w:val='99'/>
-                    <w:semiHidden/>
-                    <w:rPr>
-                      <w:rFonts w:ascii='Tahoma' w:hAnsi='Tahoma' w:cs='Tahoma'/>
-                      <w:sz w:val='16'/>
-                      <w:szCs w:val='16'/>
-                    </w:rPr>
-                  </w:style>");
-
-            part.PutXDocument();
-        }
-
-        private static void UpdateStylesPartForToc(WordprocessingDocument doc)
-        {
-            StylesPart stylesPart = doc.MainDocumentPart.StyleDefinitionsPart;
-            if (stylesPart == null)
-                return;
-            UpdatePartForToc(stylesPart);
-        }
-
-        private static void UpdateStylesWithEffectsPartForToc(WordprocessingDocument doc)
-        {
-            StylesWithEffectsPart stylesWithEffectsPart = doc.MainDocumentPart.StylesWithEffectsPart;
-            if (stylesWithEffectsPart == null)
-                return;
-            UpdatePartForToc(stylesWithEffectsPart);
-        }
-
-        private static void UpdatePartForTof(OpenXmlPart part)
-        {
-            XDocument xDoc = part.GetXDocument();
-
-            AddElementIfMissing(
-                xDoc,
-                xDoc.Root.Elements(W.style)
-                    .Where(e => (string)e.Attribute(W.type) == "paragraph" && (string)e.Attribute(W.styleId) == "TableofFigures")
-                    .FirstOrDefault(),
-                @"<w:style w:type='paragraph' w:styleId='TableofFigures' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-                    <w:name w:val='table of figures'/>
-                    <w:basedOn w:val='Normal'/>
-                    <w:next w:val='Normal'/>
-                    <w:uiPriority w:val='99'/>
-                    <w:unhideWhenUsed/>
-                    <w:pPr>
-                      <w:spacing w:after='0'/>
-                    </w:pPr>
-                  </w:style>");
-
-            AddElementIfMissing(
-                xDoc,
-                xDoc.Root.Elements(W.style)
-                    .Where(e => (string)e.Attribute(W.type) == "character" && (string)e.Attribute(W.styleId) == "Hyperlink")
-                    .FirstOrDefault(),
-                @"<w:style w:type='character' w:styleId='Hyperlink' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-                     <w:name w:val='Hyperlink'/>
-                     <w:basedOn w:val='DefaultParagraphFont'/>
-                     <w:uiPriority w:val='99'/>
-                     <w:unhideWhenUsed/>
-                     <w:rPr>
-                       <w:color w:val='0000FF' w:themeColor='hyperlink'/>
-                       <w:u w:val='single'/>
-                     </w:rPr>
-                   </w:style>");
-            part.PutXDocument();
-        }
-
-        private static void UpdateStylesPartForTof(WordprocessingDocument doc)
-        {
-            StylesPart stylesPart = doc.MainDocumentPart.StyleDefinitionsPart;
-            if (stylesPart == null)
-                return;
-            UpdatePartForTof(stylesPart);
-        }
-
-        private static void UpdateStylesWithEffectsPartForTof(WordprocessingDocument doc)
-        {
-            StylesWithEffectsPart stylesWithEffectsPart = doc.MainDocumentPart.StylesWithEffectsPart;
-            if (stylesWithEffectsPart == null)
-                return;
-            UpdatePartForTof(stylesWithEffectsPart);
-        }
-
-        private static void UpdatePartForToa(OpenXmlPart part)
-        {
-            XDocument xDoc = part.GetXDocument();
-
-            AddElementIfMissing(
-                xDoc,
-                xDoc.Root.Elements(W.style)
-                    .Where(e => (string)e.Attribute(W.type) == "paragraph" && (string)e.Attribute(W.styleId) == "TableofAuthorities")
-                    .FirstOrDefault(),
-                @"<w:style w:type='paragraph'
-                           w:styleId='TableofAuthorities'
-                           xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-                    <w:name w:val='table of authorities'/>
-                    <w:basedOn w:val='Normal'/>
-                    <w:next w:val='Normal'/>
-                    <w:uiPriority w:val='99'/>
-                    <w:semiHidden/>
-                    <w:unhideWhenUsed/>
-                    <w:rsid w:val='0090569D'/>
-                    <w:pPr>
-                      <w:spacing w:after='0'/>
-                      <w:ind w:left='220'
-                             w:hanging='220'/>
-                    </w:pPr>
-                  </w:style>");
-
-            AddElementIfMissing(
-                xDoc,
-                xDoc.Root.Elements(W.style)
-                    .Where(e => (string)e.Attribute(W.type) == "paragraph" && (string)e.Attribute(W.styleId) == "TOAHeading")
-                    .FirstOrDefault(),
-                @"<w:style w:type='paragraph'
-                           w:styleId='TOAHeading'
-                           xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
-                    <w:name w:val='toa heading'/>
-                    <w:basedOn w:val='Normal'/>
-                    <w:next w:val='Normal'/>
-                    <w:uiPriority w:val='99'/>
-                    <w:semiHidden/>
-                    <w:unhideWhenUsed/>
-                    <w:rsid w:val='0090569D'/>
-                    <w:pPr>
-                      <w:spacing w:before='120'/>
-                    </w:pPr>
-                    <w:rPr>
-                      <w:rFonts w:asciiTheme='majorHAnsi'
-                                w:eastAsiaTheme='majorEastAsia'
-                                w:hAnsiTheme='majorHAnsi'
-                                w:cstheme='majorBidi'/>
-                      <w:b/>
-                      <w:bCs/>
-                      <w:sz w:val='24'/>
-                      <w:szCs w:val='24'/>
-                    </w:rPr>
-                  </w:style>");
-
-            part.PutXDocument();
-        }
-
-        private static void UpdateStylesPartForToa(WordprocessingDocument doc)
-        {
-            StylesPart stylesPart = doc.MainDocumentPart.StyleDefinitionsPart;
-            if (stylesPart == null)
-                return;
-            UpdatePartForToa(stylesPart);
-        }
-
-        private static void UpdateStylesWithEffectsPartForToa(WordprocessingDocument doc)
-        {
-            StylesWithEffectsPart stylesWithEffectsPart = doc.MainDocumentPart.StylesWithEffectsPart;
-            if (stylesWithEffectsPart == null)
-                return;
-            UpdatePartForToa(stylesWithEffectsPart);
-        }
-    }
-}

+ 0 - 46
TEAMModelOS.SDK/Module/OpenXmlTool/RevisionAccepter.cs

@@ -1,46 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public class RevisionAccepter
-    {
-        public static WmlDocument AcceptRevisions(WmlDocument document)
-        {
-            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
-            {
-                using (WordprocessingDocument doc = streamDoc.GetWordprocessingDocument())
-                {
-                    AcceptRevisions(doc);
-                }
-                return streamDoc.GetModifiedWmlDocument();
-            }
-        }
-
-        public static void AcceptRevisions(WordprocessingDocument doc)
-        {
-            RevisionProcessor.AcceptRevisions(doc);
-        }
-
-        public static bool PartHasTrackedRevisions(OpenXmlPart part)
-        {
-            return RevisionProcessor.PartHasTrackedRevisions(part);
-        }
-
-        public static bool HasTrackedRevisions(WmlDocument document)
-        {
-            return RevisionProcessor.HasTrackedRevisions(document);
-        }
-
-        public static bool HasTrackedRevisions(WordprocessingDocument doc)
-        {
-            return RevisionProcessor.HasTrackedRevisions(doc);
-        }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 3237
TEAMModelOS.SDK/Module/OpenXmlTool/RevisionProcessor.cs


+ 0 - 105
TEAMModelOS.SDK/Module/OpenXmlTool/SSFormula.cs

@@ -1,105 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text;
-
-namespace ExcelFormula
-{
-    public class ParseFormula
-    {
-        ExcelFormula parser;
-
-        public ParseFormula(string formula)
-        {
-            parser = new ExcelFormula(formula, Console.Out);
-            bool parserResult = false;
-            try
-            {
-                parserResult = parser.Formula();
-            }
-            catch (Peg.Base.PegException)
-            {
-            }
-            if (!parserResult)
-            {
-                parser.Warning("Error processing " + formula);
-            }
-        }
-
-        public string ReplaceSheetName(string oldName, string newName)
-        {
-            StringBuilder text = new StringBuilder(parser.GetSource());
-            ReplaceNode(parser.GetRoot(), (int)EExcelFormula.SheetName, oldName, newName, text);
-            return text.ToString();
-        }
-
-        public string ReplaceRelativeCell(int rowOffset, int colOffset)
-        {
-            StringBuilder text = new StringBuilder(parser.GetSource());
-            ReplaceRelativeCell(parser.GetRoot(), rowOffset, colOffset, text);
-            return text.ToString();
-        }
-
-        // Recursive function that will replace values from last to first
-        private void ReplaceNode(Peg.Base.PegNode node, int id, string oldName, string newName, StringBuilder text)
-        {
-            if (node.next_ != null)
-                ReplaceNode(node.next_, id, oldName, newName, text);
-            if (node.id_ == id && parser.GetSource().Substring(node.match_.posBeg_, node.match_.Length) == oldName)
-            {
-                text.Remove(node.match_.posBeg_, node.match_.Length);
-                text.Insert(node.match_.posBeg_, newName);
-            }
-            else if (node.child_ != null)
-                ReplaceNode(node.child_, id, oldName, newName, text);
-        }
-
-        // Recursive function that will adjust relative cells from last to first
-        private void ReplaceRelativeCell(Peg.Base.PegNode node, int rowOffset, int colOffset, StringBuilder text)
-        {
-            if (node.next_ != null)
-                ReplaceRelativeCell(node.next_, rowOffset, colOffset, text);
-            if (node.id_ == (int)EExcelFormula.A1Row && parser.GetSource().Substring(node.match_.posBeg_, 1) != "$")
-            {
-                int rowNumber = Convert.ToInt32(parser.GetSource().Substring(node.match_.posBeg_, node.match_.Length));
-                text.Remove(node.match_.posBeg_, node.match_.Length);
-                text.Insert(node.match_.posBeg_, Convert.ToString(rowNumber + rowOffset));
-            }
-            else if (node.id_ == (int)EExcelFormula.A1Column && parser.GetSource().Substring(node.match_.posBeg_, 1) != "$")
-            {
-                int colNumber = GetColumnNumber(parser.GetSource().Substring(node.match_.posBeg_, node.match_.Length));
-                text.Remove(node.match_.posBeg_, node.match_.Length);
-                text.Insert(node.match_.posBeg_, GetColumnId(colNumber + colOffset));
-            }
-            else if (node.child_ != null)
-                ReplaceRelativeCell(node.child_, rowOffset, colOffset, text);
-        }
-
-        // Converts the column reference string to a column number (e.g. A -> 1, B -> 2)
-        private static int GetColumnNumber(string cellReference)
-        {
-            int columnNumber = 0;
-            foreach (char c in cellReference)
-            {
-                if (Char.IsLetter(c))
-                    columnNumber = columnNumber * 26 + System.Convert.ToInt32(c) - System.Convert.ToInt32('A') + 1;
-            }
-            return columnNumber;
-        }
-
-        // Translates the column number to the column reference string (e.g. 1 -> A, 2-> B)
-        private static string GetColumnId(int columnNumber)
-        {
-            string result = "";
-            do
-            {
-                result = ((char)((columnNumber - 1) % 26 + (int)'A')).ToString() + result;
-                columnNumber = (columnNumber - 1) / 26;
-            } while (columnNumber != 0);
-            return result;
-        }
-    }
-}

+ 0 - 54
TEAMModelOS.SDK/Module/OpenXmlTool/ScalarTypes.cs

@@ -1,54 +0,0 @@
-// 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.ObjectModel;
-
-namespace OpenXmlPowerTools
-{
-    internal static class DefaultScalarTypes
-    {
-        private static readonly Hashtable defaultScalarTypesHash;
-        internal static bool IsTypeInList(Collection<string> typeNames)
-        {
-            string text = PSObjectIsOfExactType(typeNames);
-            return !string.IsNullOrEmpty(text) && (PSObjectIsEnum(typeNames) || DefaultScalarTypes.defaultScalarTypesHash.ContainsKey(text));
-        }
-
-        static DefaultScalarTypes()
-        {
-            DefaultScalarTypes.defaultScalarTypesHash = new Hashtable(StringComparer.OrdinalIgnoreCase);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.String", null);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.SByte", null);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.Byte", null);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.Int16", null);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.UInt16", null);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.Int32", 10);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.UInt32", 10);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.Int64", null);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.UInt64", null);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.Char", 1);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.Single", null);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.Double", null);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.Boolean", 5);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.Decimal", null);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.IntPtr", null);
-            DefaultScalarTypes.defaultScalarTypesHash.Add("System.Security.SecureString", null);
-        }
-
-        internal static string PSObjectIsOfExactType(Collection<string> typeNames)
-        {
-            if (typeNames.Count != 0)
-            {
-                return typeNames[0];
-            }
-            return null;
-        }
-
-        internal static bool PSObjectIsEnum(Collection<string> typeNames)
-        {
-            return typeNames.Count >= 2 && !string.IsNullOrEmpty(typeNames[1]) && string.Equals(typeNames[1], "System.Enum", StringComparison.Ordinal);
-        }
-    }
-}

+ 0 - 260
TEAMModelOS.SDK/Module/OpenXmlTool/SmlCellFormatter.cs

@@ -1,260 +0,0 @@
-// 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.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Drawing;
-using System.Globalization;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public class SmlCellFormatter
-    {
-        private enum CellType
-        {
-            General,
-            Number,
-            Date,
-        };
-
-        private class FormatConfig
-        {
-            public CellType CellType;
-            public string FormatCode;
-        }
-
-        private static Dictionary<string, FormatConfig> ExcelFormatCodeToNetFormatCodeExceptionMap = new Dictionary<string, FormatConfig>()
-        {
-            {
-                "# ?/?",
-                new FormatConfig
-                {
-                    CellType = SmlCellFormatter.CellType.Number,
-                    FormatCode = "0.00",
-                }
-            },
-            {
-                "# ??/??",
-                new FormatConfig
-                {
-                    CellType = SmlCellFormatter.CellType.Number,
-                    FormatCode = "0.00",
-                }
-            },
-        };
-
-        // Up to four sections of format codes can be specified. The format codes, separated by semicolons, define the
-        // formats for positive numbers, negative numbers, zero values, and text, in that order. If only two sections are
-        // specified, the first is used for positive numbers and zeros, and the second is used for negative numbers. If only
-        // one section is specified, it is used for all numbers. To skip a section, the ending semicolon for that section shall
-        // be written.
-        public static string FormatCell(string formatCode, string value, out string color)
-        {
-            color = null;
-
-            if (formatCode == null)
-                formatCode = "General";
-
-            var splitFormatCode = formatCode.Split(';');
-            if (splitFormatCode.Length == 1)
-            {
-                double dv;
-                if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out dv))
-                {
-                    return FormatDouble(formatCode, dv, out color);
-                }
-                return value;
-            }
-            if (splitFormatCode.Length == 2)
-            {
-                double dv;
-                if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out dv))
-                {
-                    if (dv > 0)
-                    {
-                        return FormatDouble(splitFormatCode[0], dv, out color);
-                    }
-                    else
-                    {
-                        return FormatDouble(splitFormatCode[1], dv, out color);
-                    }
-                }
-                return value;
-
-            }
-            // positive, negative, zero, text
-            // _("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)
-            if (splitFormatCode.Length == 4)
-            {
-                double dv;
-                if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out dv))
-                {
-                    if (dv > 0)
-                    {
-                        var z1 = FormatDouble(splitFormatCode[0], dv, out color);
-                        return z1;
-                    }
-                    else if (dv < 0)
-                    {
-                        var z2 = FormatDouble(splitFormatCode[1], dv, out color);
-                        return z2;
-                    }
-                    else // == 0
-                    {
-                        var z3 = FormatDouble(splitFormatCode[2], dv, out color);
-                        return z3;
-                    }
-                }
-                string fmt = splitFormatCode[3].Replace("@", "{0}").Replace("\"", "");
-                try
-                {
-                    var s = string.Format(fmt, value);
-                    return s;
-                }
-                catch (Exception)
-                {
-                    return value;
-                }
-            }
-            return value;
-        }
-
-        static Regex UnderRegex = new Regex("_.");
-
-        // The following Regex transforms currency specifies into a character / string
-        // that string.Format can use to properly produce the correct text.
-        // "[$£-809]"    => "£"
-        // "[$€-2]"      => "€"
-        // "[$¥-804]"    => "¥
-        // "[$CHF-100C]" => "CHF"
-        static string s_CurrRegex = @"\[\$(?<curr>.*-).*\]";
-
-        private static string ConvertFormatCode(string formatCode)
-        {
-            var newFormatCode = formatCode
-                .Replace("mmm-", "MMM-")
-                .Replace("-mmm", "-MMM")
-                .Replace("mm-", "MM-")
-                .Replace("mmmm", "MMMM")
-                .Replace("AM/PM", "tt")
-                .Replace("m/", "M/")
-                .Replace("*", "")
-                .Replace("?", "#")
-                ;
-            var withTrimmedUnderscores = UnderRegex.Replace(newFormatCode, "");
-            var withTransformedCurrency = Regex.Replace(withTrimmedUnderscores, s_CurrRegex, m => m.Groups[1].Value.TrimEnd('-'));
-            return withTransformedCurrency;
-        }
-
-        private static string[] ValidColors = new[] {
-            "Black",
-            "Blue",
-            "Cyan",
-            "Green",
-            "Magenta",
-            "Red",
-            "White",
-            "Yellow",
-        };
-
-        private static string FormatDouble(string formatCode, double dv, out string color)
-        {
-            color = null;
-            var trimmed = formatCode.Trim();
-            if (trimmed.StartsWith("[") &&
-                trimmed.Contains("]"))
-            {
-                var colorLen = trimmed.IndexOf(']');
-                color = trimmed.Substring(1, colorLen - 1);
-                if (ValidColors.Contains(color) ||
-                    color.StartsWith("Color"))
-                {
-                    if (color.StartsWith("Color"))
-                    {
-                        var idxStr = color.Substring(5);
-                        int colorIdx;
-                        if (int.TryParse(idxStr, out colorIdx))
-                        {
-                            if (colorIdx < SmlDataRetriever.IndexedColors.Length)
-                                color = SmlDataRetriever.IndexedColors[colorIdx];
-                            else
-                                color = null;
-                        }
-                    }
-                    formatCode = trimmed.Substring(colorLen + 1);
-                }
-                else
-                    color = null;
-            }
-
-
-            if (formatCode == "General")
-                return dv.ToString(CultureInfo.InvariantCulture);
-            bool isDate = IsFormatCodeForDate(formatCode);
-            var cfc = ConvertFormatCode(formatCode);
-            if (isDate)
-            {
-                DateTime thisDate;
-                try
-                {
-                    thisDate = DateTime.FromOADate(dv);
-                }
-                catch (ArgumentException)
-                {
-                    return dv.ToString(CultureInfo.InvariantCulture);
-                }
-                if (cfc.StartsWith("[h]"))
-                {
-                    DateTime zeroHour = new DateTime(1899, 12, 30, 0, 0, 0);
-                    int deltaInHours = (int)((thisDate - zeroHour).TotalHours);
-                    var newCfc = cfc.Substring(3);
-                    var s = (deltaInHours.ToString() + thisDate.ToString(newCfc)).Trim();
-                    return s;
-                }
-                if (cfc.EndsWith(".0"))
-                {
-                    var cfc2 = cfc.Replace(".0", ":fff");
-                    var s4 = thisDate.ToString(cfc2).Trim();
-                    return s4;
-                }
-                var s2 = thisDate.ToString(cfc, CultureInfo.InvariantCulture).Trim();
-                return s2;
-            }
-            if (ExcelFormatCodeToNetFormatCodeExceptionMap.ContainsKey(formatCode))
-            {
-                FormatConfig fc = ExcelFormatCodeToNetFormatCodeExceptionMap[formatCode];
-                var s = dv.ToString(fc.FormatCode, CultureInfo.InvariantCulture).Trim();
-                return s;
-            }
-            if ((cfc.Contains('(') && cfc.Contains(')')) || cfc.Contains('-'))
-            {
-                var s3 = (-dv).ToString(cfc, CultureInfo.InvariantCulture).Trim();
-                return s3;
-            }
-            else
-            {
-                var s4 = dv.ToString(cfc, CultureInfo.InvariantCulture).Trim();
-                return s4;
-            }
-        }
-
-        private static bool IsFormatCodeForDate(string formatCode)
-        {
-            if (formatCode == "General")
-                return false;
-            return formatCode.Contains("m") ||
-                formatCode.Contains("d") ||
-                formatCode.Contains("y") ||
-                formatCode.Contains("h") ||
-                formatCode.Contains("s") ||
-                formatCode.Contains("AM") ||
-                formatCode.Contains("PM");
-        }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 1091
TEAMModelOS.SDK/Module/OpenXmlTool/SmlDataRetriever.cs


+ 0 - 308
TEAMModelOS.SDK/Module/OpenXmlTool/SmlToHtmlConverter.cs

@@ -1,308 +0,0 @@
-// 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.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Drawing;
-using System.Globalization;
-using System.Linq;
-using System.Text;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-using System.IO;
-
-namespace OpenXmlPowerTools
-{
-    public partial class SmlDocument
-    {
-        [SuppressMessage("ReSharper", "UnusedMember.Global")]
-        public XElement ConvertToHtml(SmlToHtmlConverterSettings htmlConverterSettings, string tableName)
-        {
-            return SmlToHtmlConverter.ConvertTableToHtml(this, htmlConverterSettings, tableName);
-        }
-
-        [SuppressMessage("ReSharper", "UnusedMember.Global")]
-        public XElement ConvertTableToHtml(string tableName)
-        {
-            SmlToHtmlConverterSettings settings = new SmlToHtmlConverterSettings();
-            return SmlToHtmlConverter.ConvertTableToHtml(this, settings, tableName);
-        }
-    }
-
-    [SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Global")]
-    public class SmlToHtmlConverterSettings
-    {
-        public string PageTitle;
-        public string CssClassPrefix;
-        public bool FabricateCssClasses;
-        public string GeneralCss;
-        public string AdditionalCss;
-
-        public SmlToHtmlConverterSettings()
-        {
-            PageTitle = "";
-            CssClassPrefix = "pt-";
-            FabricateCssClasses = true;
-            GeneralCss = "span { white-space: pre-wrap; }";
-            AdditionalCss = "";
-        }
-
-        public SmlToHtmlConverterSettings(SmlToHtmlConverterSettings htmlConverterSettings)
-        {
-            PageTitle = htmlConverterSettings.PageTitle;
-            CssClassPrefix = htmlConverterSettings.CssClassPrefix;
-            FabricateCssClasses = htmlConverterSettings.FabricateCssClasses;
-            GeneralCss = htmlConverterSettings.GeneralCss;
-            AdditionalCss = htmlConverterSettings.AdditionalCss;
-        }
-    }
-
-    public static class SmlToHtmlConverter
-    {
-        // ***********************************************************************************************************************************
-        #region PublicApis
-        public static XElement ConvertTableToHtml(SmlDocument smlDoc, SmlToHtmlConverterSettings settings, string tableName)
-        {
-            using (MemoryStream ms = new MemoryStream())
-            {
-                ms.Write(smlDoc.DocumentByteArray, 0, smlDoc.DocumentByteArray.Length);
-                using (SpreadsheetDocument sDoc = SpreadsheetDocument.Open(ms, false))
-                {
-                    var rangeXml = SmlDataRetriever.RetrieveTable(sDoc, tableName);
-                    var xhtml = SmlToHtmlConverter.ConvertToHtmlInternal(sDoc, settings, rangeXml);
-                    return xhtml;
-                }
-            }
-        }
-
-        public static XElement ConvertTableToHtml(SpreadsheetDocument sDoc, SmlToHtmlConverterSettings settings, string tableName)
-        {
-            var rangeXml = SmlDataRetriever.RetrieveTable(sDoc, tableName);
-            var xhtml = SmlToHtmlConverter.ConvertToHtmlInternal(sDoc, settings, rangeXml);
-            return xhtml;
-        }
-        #endregion
-        // ***********************************************************************************************************************************
-
-        private static XElement ConvertToHtmlInternal(SpreadsheetDocument sDoc, SmlToHtmlConverterSettings htmlConverterSettings, XElement rangeXml)
-        {
-            XElement xhtml = (XElement)ConvertToHtmlTransform(sDoc, htmlConverterSettings, rangeXml);
-
-            ReifyStylesAndClasses(htmlConverterSettings, xhtml);
-
-            // Note: the xhtml returned by ConvertToHtmlTransform contains objects of type
-            // XEntity.  PtOpenXmlUtil.cs define the XEntity class.  See
-            // http://blogs.msdn.com/ericwhite/archive/2010/01/21/writing-entity-references-using-linq-to-xml.aspx
-            // for detailed explanation.
-            //
-            // If you further transform the XML tree returned by ConvertToHtmlTransform, you
-            // must do it correctly, or entities will not be serialized properly.
-
-            return xhtml;
-        }
-
-        private static XNode ConvertToHtmlTransform(SpreadsheetDocument sDoc, SmlToHtmlConverterSettings htmlConverterSettings, XNode node)
-        {
-            var element = node as XElement;
-            if (element != null)
-            {
-                return new XElement(element.Name,
-                    element.Attributes(),
-                    element.Nodes().Select(n => ConvertToHtmlTransform(sDoc, htmlConverterSettings, n)));
-            }
-            return node;
-        }
-
-        private static void ReifyStylesAndClasses(SmlToHtmlConverterSettings htmlConverterSettings, XElement xhtml)
-        {
-            if (htmlConverterSettings.FabricateCssClasses)
-            {
-                var usedCssClassNames = new HashSet<string>();
-                var elementsThatNeedClasses = xhtml
-                    .DescendantsAndSelf()
-                    .Select(d => new
-                    {
-                        Element = d,
-                        Styles = d.Annotation<Dictionary<string, string>>(),
-                    })
-                    .Where(z => z.Styles != null);
-                var augmented = elementsThatNeedClasses
-                    .Select(p => new
-                    {
-                        p.Element,
-                        p.Styles,
-                        StylesString = p.Element.Name.LocalName + "|" + p.Styles.OrderBy(k => k.Key).Select(s => string.Format("{0}: {1};", s.Key, s.Value)).StringConcatenate(),
-                    })
-                    .GroupBy(p => p.StylesString)
-                    .ToList();
-                int classCounter = 1000000;
-                var sb = new StringBuilder();
-                sb.Append(Environment.NewLine);
-                foreach (var grp in augmented)
-                {
-                    string classNameToUse;
-                    var firstOne = grp.First();
-                    var styles = firstOne.Styles;
-                    if (styles.ContainsKey("PtStyleName"))
-                    {
-                        classNameToUse = htmlConverterSettings.CssClassPrefix + styles["PtStyleName"];
-                        if (usedCssClassNames.Contains(classNameToUse))
-                        {
-                            classNameToUse = htmlConverterSettings.CssClassPrefix +
-                                styles["PtStyleName"] + "-" +
-                                classCounter.ToString().Substring(1);
-                            classCounter++;
-                        }
-                    }
-                    else
-                    {
-                        classNameToUse = htmlConverterSettings.CssClassPrefix +
-                            classCounter.ToString().Substring(1);
-                        classCounter++;
-                    }
-                    usedCssClassNames.Add(classNameToUse);
-                    sb.Append(firstOne.Element.Name.LocalName + "." + classNameToUse + " {" + Environment.NewLine);
-                    foreach (var st in firstOne.Styles.Where(s => s.Key != "PtStyleName"))
-                    {
-                        var s = "    " + st.Key + ": " + st.Value + ";" + Environment.NewLine;
-                        sb.Append(s);
-                    }
-                    sb.Append("}" + Environment.NewLine);
-                    var classAtt = new XAttribute("class", classNameToUse);
-                    foreach (var gc in grp)
-                        gc.Element.Add(classAtt);
-                }
-                var styleValue = htmlConverterSettings.GeneralCss + sb + htmlConverterSettings.AdditionalCss;
-
-                SetStyleElementValue(xhtml, styleValue);
-            }
-            else
-            {
-                // Previously, the h:style element was not added at this point. However,
-                // at least the General CSS will contain important settings.
-                SetStyleElementValue(xhtml, htmlConverterSettings.GeneralCss + htmlConverterSettings.AdditionalCss);
-
-                foreach (var d in xhtml.DescendantsAndSelf())
-                {
-                    var style = d.Annotation<Dictionary<string, string>>();
-                    if (style == null)
-                        continue;
-                    var styleValue =
-                        style
-                        .Where(p => p.Key != "PtStyleName")
-                        .OrderBy(p => p.Key)
-                        .Select(e => string.Format("{0}: {1};", e.Key, e.Value))
-                        .StringConcatenate();
-                    XAttribute st = new XAttribute("style", styleValue);
-                    if (d.Attribute("style") != null)
-                        d.Attribute("style").Value += styleValue;
-                    else
-                        d.Add(st);
-                }
-            }
-        }
-
-        private static void SetStyleElementValue(XElement xhtml, string styleValue)
-        {
-            var styleElement = xhtml
-                .Descendants(Xhtml.style)
-                .FirstOrDefault();
-            if (styleElement != null)
-                styleElement.Value = styleValue;
-            else
-            {
-                styleElement = new XElement(Xhtml.style, styleValue);
-                var head = xhtml.Element(Xhtml.head);
-                if (head != null)
-                    head.Add(styleElement);
-            }
-        }
-
-        private static object ConvertToHtmlTransform(WordprocessingDocument wordDoc,
-            WmlToHtmlConverterSettings settings, XNode node)
-        {
-            // Ignore element.
-            return null;
-        }
-
-        private static readonly HashSet<string> UnknownFonts = new HashSet<string>();
-        private static HashSet<string> _knownFamilies;
-
-        private static HashSet<string> KnownFamilies
-        {
-            get
-            {
-                if (_knownFamilies == null)
-                {
-                    _knownFamilies = new HashSet<string>();
-                    var families = FontFamily.Families;
-                    foreach (var fam in families)
-                        _knownFamilies.Add(fam.Name);
-                }
-                return _knownFamilies;
-            }
-        }
-
-        private static readonly Dictionary<string, string> FontFallback = new Dictionary<string, string>()
-        {
-            { "Arial", @"'{0}', 'sans-serif'" },
-            { "Arial Narrow", @"'{0}', 'sans-serif'" },
-            { "Arial Rounded MT Bold", @"'{0}', 'sans-serif'" },
-            { "Arial Unicode MS", @"'{0}', 'sans-serif'" },
-            { "Baskerville Old Face", @"'{0}', 'serif'" },
-            { "Berlin Sans FB", @"'{0}', 'sans-serif'" },
-            { "Berlin Sans FB Demi", @"'{0}', 'sans-serif'" },
-            { "Calibri Light", @"'{0}', 'sans-serif'" },
-            { "Gill Sans MT", @"'{0}', 'sans-serif'" },
-            { "Gill Sans MT Condensed", @"'{0}', 'sans-serif'" },
-            { "Lucida Sans", @"'{0}', 'sans-serif'" },
-            { "Lucida Sans Unicode", @"'{0}', 'sans-serif'" },
-            { "Segoe UI", @"'{0}', 'sans-serif'" },
-            { "Segoe UI Light", @"'{0}', 'sans-serif'" },
-            { "Segoe UI Semibold", @"'{0}', 'sans-serif'" },
-            { "Tahoma", @"'{0}', 'sans-serif'" },
-            { "Trebuchet MS", @"'{0}', 'sans-serif'" },
-            { "Verdana", @"'{0}', 'sans-serif'" },
-            { "Book Antiqua", @"'{0}', 'serif'" },
-            { "Bookman Old Style", @"'{0}', 'serif'" },
-            { "Californian FB", @"'{0}', 'serif'" },
-            { "Cambria", @"'{0}', 'serif'" },
-            { "Constantia", @"'{0}', 'serif'" },
-            { "Garamond", @"'{0}', 'serif'" },
-            { "Lucida Bright", @"'{0}', 'serif'" },
-            { "Lucida Fax", @"'{0}', 'serif'" },
-            { "Palatino Linotype", @"'{0}', 'serif'" },
-            { "Times New Roman", @"'{0}', 'serif'" },
-            { "Wide Latin", @"'{0}', 'serif'" },
-            { "Courier New", @"'{0}'" },
-            { "Lucida Console", @"'{0}'" },
-        };
-
-        private static void CreateFontCssProperty(string font, Dictionary<string, string> style)
-        {
-            if (FontFallback.ContainsKey(font))
-            {
-                style.AddIfMissing("font-family", string.Format(FontFallback[font], font));
-                return;
-            }
-            style.AddIfMissing("font-family", font);
-        }
-
-        private static bool GetBoolProp(XElement runProps, XName xName)
-        {
-            var p = runProps.Element(xName);
-            if (p == null)
-                return false;
-            var v = p.Attribute(W.val);
-            if (v == null)
-                return true;
-            var s = v.Value.ToLower();
-            if (s == "0" || s == "false")
-                return false;
-            if (s == "1" || s == "true")
-                return true;
-            return false;
-        }
-    }
-}

+ 0 - 208
TEAMModelOS.SDK/Module/OpenXmlTool/SpreadsheetDocumentManager.cs

@@ -1,208 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    /// <summary>
-    /// Manages SpreadsheetDocument content
-    /// </summary>
-    public class SpreadsheetDocumentManager
-    {
-        private static XNamespace ns;
-        private static XNamespace relationshipsns;
-        private static int headerRow = 1;
-
-        static SpreadsheetDocumentManager()
-        {
-            ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
-            relationshipsns = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
-        }
-
-        /// <summary>
-        /// Creates a spreadsheet document from a value table
-        /// </summary>
-        /// <param name="filePath">Path to store the document</param>
-        /// <param name="headerList">Contents of first row (header)</param>
-        /// <param name="valueTable">Contents of data</param>
-        /// <param name="initialRow">Row to start copying data from</param>
-        /// <returns></returns>
-        public static void Create(SpreadsheetDocument document, List<string> headerList, string[][] valueTable, int initialRow)
-        {
-            headerRow = initialRow;
-
-            //Creates a worksheet with given data
-            WorksheetPart worksheet = WorksheetAccessor.Create(document, headerList, valueTable, headerRow);
-        }
-
-        /// <summary>
-        /// Creates a spreadsheet document with a chart from a value table
-        /// </summary>
-        /// <param name="filePath">Path to store the document</param>
-        /// <param name="headerList">Contents of first row (header)</param>
-        /// <param name="valueTable">Contents of data</param>
-        /// <param name="chartType">Chart type</param>
-        /// <param name="categoryColumn">Column to use as category for charting</param>
-        /// <param name="columnsToChart">Columns to use as data series</param>
-        /// <param name="initialRow">Row index to start copying data</param>
-        /// <returns>SpreadsheetDocument</returns>
-        //public static void Create(SpreadsheetDocument document, List<string> headerList, string[][] valueTable, ChartType chartType, string categoryColumn, List<string> columnsToChart, int initialRow)
-        //{
-        //    headerRow = initialRow;
-
-        //    //Creates worksheet with data
-        //    WorksheetPart worksheet = WorksheetAccessor.Create(document, headerList, valueTable, headerRow);
-        //    //Creates chartsheet with given series and category
-        //    string sheetName = GetSheetName(worksheet, document);
-        //    ChartsheetPart chartsheet =
-        //        ChartsheetAccessor.Create(document,
-        //            chartType,
-        //            GetValueReferences(sheetName, categoryColumn, headerList, columnsToChart, valueTable),
-        //            GetHeaderReferences(sheetName, categoryColumn, headerList, columnsToChart, valueTable),
-        //            GetCategoryReference(sheetName, categoryColumn, headerList, valueTable)
-        //        );
-        //}
-
-        /// <summary>
-        /// Gets the internal name of a worksheet from a document
-        /// </summary>
-        private static string GetSheetName(WorksheetPart worksheet, SpreadsheetDocument document)
-        {
-            //Gets the id of worksheet part
-            string partId = document.WorkbookPart.GetIdOfPart(worksheet);
-            XDocument workbookDocument = document.WorkbookPart.GetXDocument();
-            //Gets the name from sheet tag related to worksheet
-            string sheetName =
-                workbookDocument.Root
-                .Element(ns + "sheets")
-                .Elements(ns + "sheet")
-                .Where(
-                    t =>
-                        t.Attribute(relationshipsns + "id").Value == partId
-                ).First()
-                .Attribute("name").Value;
-            return sheetName;
-        }
-        /// <summary>
-        /// Gets the range reference for category
-        /// </summary>
-        /// <param name="sheetName">worksheet to take data from</param>
-        /// <param name="headerColumn">name of column used as category</param>
-        /// <param name="headerList">column names from data</param>
-        /// <param name="valueTable">Data values</param>
-        /// <returns></returns>
-        private static string GetCategoryReference(string sheetName, string headerColumn, List<string> headerList, string[][] valueTable)
-        {
-            int categoryColumn = headerList.IndexOf(headerColumn.ToUpper()) + 1;
-            int numRows = valueTable.GetLength(0);
-
-            return GetRangeReference(
-                sheetName,
-                categoryColumn,
-                headerRow + 1,
-                categoryColumn,
-                numRows + headerRow
-            );
-        }
-
-        /// <summary>
-        /// Gets a list of range references for each of the series headers
-        /// </summary>
-        /// <param name="sheetName">worksheet to take data from</param>
-        /// <param name="headerColumn">name of column used as category</param>
-        /// <param name="headerList">column names from data</param>
-        /// <param name="valueTable">Data values</param>
-        /// <param name="colsToChart">Columns used as data series</param>
-        /// <returns></returns>
-        private static List<string> GetHeaderReferences(string sheetName, string headerColumn, List<string> headerList, List<string> colsToChart, string[][] valueTable)
-        {
-            List<string> valueReferenceList = new List<string>();
-
-            foreach (string column in colsToChart)
-            {
-                valueReferenceList.Add(
-                    GetRangeReference(
-                        sheetName,
-                        headerList.IndexOf(column.ToUpper()) + 1,
-                        headerRow
-                    )
-                );
-            }
-            return valueReferenceList;
-        }
-
-        /// <summary>
-        /// Gets a list of range references for each of the series values
-        /// </summary>
-        /// <param name="sheetName">worksheet to take data from</param>
-        /// <param name="headerColumn">name of column used as category</param>
-        /// <param name="headerList">column names from data</param>
-        /// <param name="valueTable">Data values</param>
-        /// <param name="colsToChart">Columns used as data series</param>
-        /// <returns></returns>
-        private static List<string> GetValueReferences(string sheetName, string headerColumn, List<string> headerList, List<string> colsToChart, string[][] valueTable)
-        {
-            List<string> valueReferenceList = new List<string>();
-            int numRows = valueTable.GetLength(0);
-
-            foreach (string column in colsToChart)
-            {
-                int dataColumn = headerList.IndexOf(column.ToUpper()) + 1;
-                valueReferenceList.Add(
-                    GetRangeReference(
-                        sheetName,
-                        dataColumn,
-                        headerRow + 1,
-                        dataColumn,
-                        numRows + headerRow
-                    )
-                );
-            }
-            return valueReferenceList;
-        }
-
-        /// <summary>
-        /// Gets a formatted representation of a cell range from a worksheet
-        /// </summary>
-        private static string GetRangeReference(string worksheet, int column, int row)
-        {
-            return string.Format("{0}!{1}{2}", worksheet, WorksheetAccessor.GetColumnId(column), row);
-        }
-
-        /// <summary>
-        /// Gets a formatted representation of a cell range from a worksheet
-        /// </summary>
-        private static string GetRangeReference(string worksheet, int startColumn, int startRow, int endColumn, int endRow)
-        {
-            return string.Format("{0}!{1}{2}:{3}{4}",
-                worksheet,
-                WorksheetAccessor.GetColumnId(startColumn),
-                startRow,
-                WorksheetAccessor.GetColumnId(endColumn),
-                endRow
-            );
-        }
-
-        /// <summary>
-        /// Creates an empty (base) workbook document
-        /// </summary>
-        /// <returns></returns>
-        private static XDocument CreateEmptyWorkbook()
-        {
-            XDocument document =
-                new XDocument(
-                    new XElement(ns + "workbook",
-                        new XAttribute("xmlns", ns),
-                        new XAttribute(XNamespace.Xmlns + "r", relationshipsns),
-                        new XElement(ns + "sheets")
-                    )
-                );
-
-            return document;
-        }
-    }
-}

+ 0 - 781
TEAMModelOS.SDK/Module/OpenXmlTool/SpreadsheetWriter.cs

@@ -1,781 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-#undef DisplayWorkingSet
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text.RegularExpressions;
-using System.Xml;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-using OpenXmlPowerTools;
-
-namespace OpenXmlPowerTools
-{
-    // The classes in SpreadsheetWriter are still a work-in-progress.  While they are useful in their current state, I will be enhancing and
-    // changing them in the future.  In particular, I will be augmenting the various definition classes (WorkbookDfn, WorksheetDfn,
-    // RowDfn, and CellDfn.
-    
-    // They are robust enough in their current form to be used in enterprise, mission critical.
-
-    public class WorkbookDfn
-    {
-        public IEnumerable<WorksheetDfn> Worksheets;
-    }
-
-    public class WorksheetDfn
-    {
-        public string Name;
-        public string TableName;
-        public IEnumerable<CellDfn> ColumnHeadings;
-        public IEnumerable<RowDfn> Rows;
-    }
-
-    public class RowDfn
-    {
-        public IEnumerable<CellDfn> Cells;
-    }
-
-    // Value can be:
-    // - string
-    // - bool
-    // - DateTime
-    // - int32, int64, uint, double, float, etc.
-
-    // Standard formats
-    public class CellDfn
-    {
-        public static Dictionary<string, int> StandardFormats = new Dictionary<string, int>
-        {
-            { "0",                        1   },
-            { "0.00",                     2   },
-            { "#,##0",                    3   },
-            { "#,##0.00",                 4   },
-            { "0%",                       9   },
-            { "0.00%",                    10  },
-            { "0.00E+00",                 11  },
-            { "# ?/?",                    12  },
-            { "# ??/??",                  13  },
-            { "mm-dd-yy",                 14  },
-            { "d-mmm-yy",                 15  },
-            { "d-mmm",                    16  },
-            { "mmm-yy",                   17  },
-            { "h:mm AM/PM",               18  },
-            { "h:mm:ss AM/PM",            19  },
-            { "h:mm",                     20  },
-            { "h:mm:ss",                  21  },
-            { "h/d/yy h:mm",              22  },
-            { "#,##0;(#,##0)",            37  },
-            { "#,##0;[Red](#,##0)",       38  },
-            { "#,##0.00;(#,##0.00)",      39  },
-            { "#,##0.00;[Red](#,##0.00)", 40  },
-            { "mm:ss",                    45  },
-            { "[h]:mm:ss",                46  },
-            { "mmss.0",                   47  },
-            { "##0.0E+0",                 48  },
-            { "@",                        49  },
-        };
-        public object Value;
-        public CellDataType? CellDataType;
-        public HorizontalCellAlignment? HorizontalCellAlignment;
-        public bool? Bold;
-        public bool? Italic;
-        public string FormatCode;
-    }
-
-    public enum HorizontalCellAlignment
-    {
-        Left,
-        Center,
-        Right,
-    }
-
-    public enum CellDataType
-    {
-        Boolean,
-        Date,
-        Number,
-        String,
-    }
-
-    public static class SpreadsheetWriter
-    {
-        public static void Write(string fileName, WorkbookDfn workbook)
-        {
-            try
-            {
-                if (fileName == null) throw new ArgumentNullException("fileName");
-                if (workbook == null) throw new ArgumentNullException("workbook");
-
-                FileInfo fi = new FileInfo(fileName);
-                if (fi.Exists)
-                    fi.Delete();
-
-                // create the blank workbook
-                char[] base64CharArray = _EmptyXlsx
-                    .Where(c => c != '\r' && c != '\n').ToArray();
-                byte[] byteArray =
-                    System.Convert.FromBase64CharArray(base64CharArray,
-                    0, base64CharArray.Length);
-                File.WriteAllBytes(fi.FullName, byteArray);
-
-                // open the workbook, and create the TableProperties sheet, populate it
-                using (SpreadsheetDocument sDoc = SpreadsheetDocument.Open(fi.FullName, true))
-                {
-                    WorkbookPart workbookPart = sDoc.WorkbookPart;
-                    XDocument wXDoc = workbookPart.GetXDocument();
-                    XElement sheetElement = wXDoc
-                        .Root
-                        .Elements(S.sheets)
-                        .Elements(S.sheet)
-                        .Where(s => (string)s.Attribute(SSNoNamespace.name) == "Sheet1")
-                        .FirstOrDefault();
-                    if (sheetElement == null)
-                        throw new SpreadsheetWriterInternalException();
-                    string id = (string)sheetElement.Attribute(R.id);
-                    sheetElement.Remove();
-                    workbookPart.PutXDocument();
-
-                    WorksheetPart sPart = (WorksheetPart)workbookPart.GetPartById(id);
-                    workbookPart.DeletePart(sPart);
-
-                    XDocument appXDoc = sDoc
-                        .ExtendedFilePropertiesPart
-                        .GetXDocument();
-                    XElement vector = appXDoc
-                        .Root
-                        .Elements(EP.TitlesOfParts)
-                        .Elements(VT.vector)
-                        .FirstOrDefault();
-                    if (vector != null)
-                    {
-                        vector.SetAttributeValue(SSNoNamespace.size, 0);
-                        XElement lpstr = vector.Element(VT.lpstr);
-                        lpstr.Remove();
-                    }
-                    XElement vector2 = appXDoc
-                        .Root
-                        .Elements(EP.HeadingPairs)
-                        .Elements(VT.vector)
-                        .FirstOrDefault();
-                    XElement variant = vector2
-                        .Descendants(VT.i4)
-                        .FirstOrDefault();
-                    if (variant != null)
-                        variant.Value = "1";
-                    sDoc.ExtendedFilePropertiesPart.PutXDocument();
-
-                    if (workbook.Worksheets != null)
-                        foreach (var worksheet in workbook.Worksheets)
-                            AddWorksheet(sDoc, worksheet);
-
-                    workbookPart.WorkbookStylesPart.PutXDocument();
-                }
-            }
-            catch (Exception e)
-            {
-                Console.WriteLine("Unhandled exception: {0} in {1}",
-                    e.ToString(), e.Source);
-                throw e;
-            }
-        }
-
-        public static void AddWorksheet(SpreadsheetDocument sDoc, WorksheetDfn worksheetData)
-        {
-            Regex validSheetName = new Regex(@"^[^'*\[\]/\\:?][^*\[\]/\\:?]{0,30}$");
-            if (!validSheetName.IsMatch(worksheetData.Name))
-                throw new InvalidSheetNameException(worksheetData.Name);
-
-            // throw WorksheetAlreadyExistsException if a sheet with the same name (case-insensitive) already exists in the workbook
-            string UCName = worksheetData.Name.ToUpper();
-            XDocument wXDoc = sDoc.WorkbookPart.GetXDocument();
-            if (wXDoc
-                .Root
-                .Elements(S.sheets)
-                .Elements(S.sheet)
-                .Attributes(SSNoNamespace.name)
-                .Select(a => ((string)a).ToUpper())
-                .Contains(UCName))
-                throw new WorksheetAlreadyExistsException(worksheetData.Name);
-
-            // create the worksheet with the supplied name
-            XDocument appXDoc = sDoc
-                .ExtendedFilePropertiesPart
-                .GetXDocument();
-            XElement vector = appXDoc
-                .Root
-                .Elements(EP.TitlesOfParts)
-                .Elements(VT.vector)
-                .FirstOrDefault();
-            if (vector != null)
-            {
-                int? size = (int?)vector.Attribute(SSNoNamespace.size);
-                if (size == null)
-                    size = 1;
-                else
-                    size = size + 1;
-                vector.SetAttributeValue(SSNoNamespace.size, size);
-                vector.Add(
-                    new XElement(VT.lpstr, worksheetData.Name));
-                XElement i4 = appXDoc
-                    .Root
-                    .Elements(EP.HeadingPairs)
-                    .Elements(VT.vector)
-                    .Elements(VT.variant)
-                    .Elements(VT.i4)
-                    .FirstOrDefault();
-                if (i4 != null)
-                    i4.Value = ((int)i4 + 1).ToString();
-                sDoc.ExtendedFilePropertiesPart.PutXDocument();
-            }
-
-            WorkbookPart workbook = sDoc.WorkbookPart;
-            string rId = "R" + Guid.NewGuid().ToString().Replace("-", "");
-            WorksheetPart worksheetPart = workbook.AddNewPart<WorksheetPart>(rId);
-
-            XDocument wbXDoc = workbook.GetXDocument();
-            XElement sheets = wbXDoc.Descendants(S.sheets).FirstOrDefault();
-            sheets.Add(
-                new XElement(S.sheet,
-                    new XAttribute(SSNoNamespace.name, worksheetData.Name.ToString()),
-                    new XAttribute(SSNoNamespace.sheetId, sheets.Elements(S.sheet).Count() + 1),
-                    new XAttribute(R.id, rId)));
-            workbook.PutXDocument();
-
-            string ws = S.s.ToString();
-            string relns = R.r.ToString();
-
-            using (Stream partStream = worksheetPart.GetStream(FileMode.Create, FileAccess.Write))
-            {
-                using (XmlWriter partXmlWriter = XmlWriter.Create(partStream))
-                {
-                    partXmlWriter.WriteStartDocument();
-                    partXmlWriter.WriteStartElement("worksheet", ws);
-                    partXmlWriter.WriteStartElement("sheetData", ws);
-
-                    int numColumnHeadingRows = 0;
-                    int numColumns = 0;
-                    int numColumnsInRows = 0;
-                    int numRows;
-                    if (worksheetData.ColumnHeadings != null)
-                    {
-                        RowDfn row = new RowDfn
-                        {
-                            Cells = worksheetData.ColumnHeadings
-                        };
-                        SerializeRows(sDoc, partXmlWriter, new[] { row }, 1, out numColumns, out numColumnHeadingRows);
-                    }
-                    SerializeRows(sDoc, partXmlWriter, worksheetData.Rows, numColumnHeadingRows + 1, out numColumnsInRows,
-                        out numRows);
-                    int totalRows = numColumnHeadingRows + numRows;
-                    int totalColumns = Math.Max(numColumns, numColumnsInRows);
-                    if (worksheetData.ColumnHeadings != null && worksheetData.TableName != null)
-                    {
-                        partXmlWriter.WriteEndElement();
-                        string rId2 = "R" + Guid.NewGuid().ToString().Replace("-", "");
-                        partXmlWriter.WriteStartElement("tableParts", ws);
-                        partXmlWriter.WriteStartAttribute("count");
-                        partXmlWriter.WriteValue(1);
-                        partXmlWriter.WriteEndAttribute();
-                        partXmlWriter.WriteStartElement("tablePart", ws);
-                        partXmlWriter.WriteStartAttribute("id", relns);
-                        partXmlWriter.WriteValue(rId2);
-                        TableDefinitionPart tdp = worksheetPart.AddNewPart<TableDefinitionPart>(rId2);
-                        XDocument tXDoc = tdp.GetXDocument();
-                        XElement table = new XElement(S.table,
-                            new XAttribute(SSNoNamespace.id, 1),
-                            new XAttribute(SSNoNamespace.name, worksheetData.TableName),
-                            new XAttribute(SSNoNamespace.displayName, worksheetData.TableName),
-                            new XAttribute(SSNoNamespace._ref, "A1:" + SpreadsheetMLUtil.IntToColumnId(totalColumns - 1) + totalRows.ToString()),
-                            new XAttribute(SSNoNamespace.totalsRowShown, 0),
-                            new XElement(S.autoFilter,
-                                new XAttribute(SSNoNamespace._ref, "A1:" + SpreadsheetMLUtil.IntToColumnId(totalColumns - 1) + totalRows.ToString())),
-                            new XElement(S.tableColumns,
-                                new XAttribute(SSNoNamespace.count, totalColumns),
-                                worksheetData.ColumnHeadings.Select((ch, i) =>
-                                    new XElement(S.tableColumn,
-                                        new XAttribute(SSNoNamespace.id, i + 1),
-                                        new XAttribute(SSNoNamespace.name, ch.Value)))),
-                            new XElement(S.tableStyleInfo,
-                                new XAttribute(SSNoNamespace.name, "TableStyleMedium2"),
-                                new XAttribute(SSNoNamespace.showFirstColumn, 0),
-                                new XAttribute(SSNoNamespace.showLastColumn, 0),
-                                new XAttribute(SSNoNamespace.showRowStripes, 1),
-                                new XAttribute(SSNoNamespace.showColumnStripes, 0)));
-                        tXDoc.Add(table);
-                        tdp.PutXDocument();
-                    }
-                }
-            }
-            sDoc.WorkbookPart.WorkbookStylesPart.PutXDocument();
-            sDoc.WorkbookPart.WorkbookStylesPart.Stylesheet.Save();
-        }
-
-        private static void SerializeRows(SpreadsheetDocument sDoc, XmlWriter xmlWriter, IEnumerable<RowDfn> rows,
-            int startingRowNumber, out int numColumns, out int numRows)
-        {
-            int rowCount = 0;
-            int rowNumber = startingRowNumber;
-            int maxColumns = 0;
-            int localNumColumns;
-#if DisplayWorkingSet
-            int workingSetInterval = 10000;
-            int workingSetCount = 0;
-#endif
-            foreach (var row in rows)
-            {
-                SerializeRow(sDoc, xmlWriter, rowNumber, row, out localNumColumns);
-                maxColumns = Math.Max(maxColumns, localNumColumns);
-                rowNumber++;
-                rowCount++;
-#if DisplayWorkingSet
-                if (workingSetCount++ > workingSetInterval)
-                {
-                    workingSetCount = 0;
-                    Console.WriteLine(Environment.WorkingSet);
-                }
-#endif
-            }
-            numColumns = maxColumns;
-            numRows = rowCount;
-        }
-
-        private static void SerializeRow(SpreadsheetDocument sDoc, XmlWriter xw, int rowCount, RowDfn row, out int numColumns)
-        {
-            string ns = S.s.NamespaceName;
-
-            xw.WriteStartElement("row", ns);
-            xw.WriteStartAttribute("r");
-            xw.WriteValue(rowCount);
-            xw.WriteEndAttribute();
-            xw.WriteStartAttribute("spans");
-            xw.WriteValue("1:" + row.Cells.Count().ToString());
-            xw.WriteEndAttribute();
-            int cellCount = 0;
-            foreach (var cell in row.Cells)
-            {
-                if (cell != null)
-                {
-                    xw.WriteStartElement("c", ns);
-                    xw.WriteStartAttribute("r");
-                    xw.WriteValue(SpreadsheetMLUtil.IntToColumnId(cellCount) + rowCount.ToString());
-                    xw.WriteEndAttribute();
-                    if (cell.Bold != null ||
-                        cell.Italic != null ||
-                        cell.FormatCode != null ||
-                        cell.HorizontalCellAlignment != null)
-                    {
-                        xw.WriteStartAttribute("s");
-                        xw.WriteValue(GetCellStyle(sDoc, cell));
-                        xw.WriteEndAttribute();
-                    }
-                    switch (cell.CellDataType)
-                    {
-                        case CellDataType.Boolean:
-                            xw.WriteStartAttribute("t");
-                            xw.WriteValue("b");
-                            xw.WriteEndAttribute();
-                            break;
-                        case CellDataType.Date:
-                            xw.WriteStartAttribute("t");
-                            xw.WriteValue("d");
-                            xw.WriteEndAttribute();
-                            break;
-                        case CellDataType.Number:
-                            xw.WriteStartAttribute("t");
-                            xw.WriteValue("n");
-                            xw.WriteEndAttribute();
-                            break;
-                        case CellDataType.String:
-                            xw.WriteStartAttribute("t");
-                            xw.WriteValue("str");
-                            xw.WriteEndAttribute();
-                            break;
-                        default:
-                            xw.WriteStartAttribute("t");
-                            xw.WriteValue("str");
-                            xw.WriteEndAttribute();
-                            break;
-                    }
-                    if (cell.Value != null)
-                    {
-                        xw.WriteStartElement("v", ns);
-                        xw.WriteValue(cell.Value);
-                        xw.WriteEndElement();
-                    }
-                    xw.WriteEndElement();
-                }
-                cellCount++;
-            }
-            xw.WriteEndElement();
-            numColumns = cellCount;
-        }
-
-        private static int GetCellStyle(SpreadsheetDocument sDoc, CellDfn cell)
-        {
-            XDocument sXDoc = sDoc.WorkbookPart.WorkbookStylesPart.GetXDocument();
-            var match = sXDoc
-                .Root
-                .Element(S.cellXfs)
-                .Elements(S.xf)
-                .Select((e, i) => new
-                {
-                    Element = e,
-                    Index = i,
-                })
-                .FirstOrDefault(xf => CompareStyles(sXDoc, xf.Element, cell));
-            if (match != null)
-                return match.Index;
-
-            // if no match, then create a style
-            int newId = CreateNewStyle(sXDoc, cell, sDoc);
-            return newId;
-        }
-
-        private static int CreateNewStyle(XDocument sXDoc, CellDfn cell, SpreadsheetDocument sDoc)
-        {
-            XAttribute applyFont = null;
-            XAttribute fontId = null;
-            if (cell.Bold == true || cell.Italic == true)
-            {
-                applyFont = new XAttribute(SSNoNamespace.applyFont, 1);
-                fontId = new XAttribute(SSNoNamespace.fontId, GetFontId(sXDoc, cell));
-            }
-            XAttribute applyAlignment = null;
-            XElement alignment = null;
-            if (cell.HorizontalCellAlignment != null)
-            {
-                applyAlignment = new XAttribute(SSNoNamespace.applyAlignment, 1);
-                alignment = new XElement(S.alignment,
-                    new XAttribute(SSNoNamespace.horizontal, cell.HorizontalCellAlignment.ToString().ToLower()));
-            }
-            XAttribute applyNumberFormat = null;
-            XAttribute numFmtId = null;
-            if (cell.FormatCode != null)
-            {
-                if (CellDfn.StandardFormats.ContainsKey(cell.FormatCode))
-                {
-                    applyNumberFormat = new XAttribute(SSNoNamespace.applyNumberFormat, 1);
-                    numFmtId = new XAttribute(SSNoNamespace.numFmtId, CellDfn.StandardFormats[cell.FormatCode]);
-                }
-                else
-                {
-                    applyNumberFormat = new XAttribute(SSNoNamespace.applyNumberFormat, 1);
-                    numFmtId = new XAttribute(SSNoNamespace.numFmtId, GetNumFmtId(sXDoc, cell.FormatCode));
-                }
-            }
-            XElement newXf = new XElement(S.xf,
-                applyFont,
-                fontId,
-                applyAlignment,
-                alignment,
-                applyNumberFormat,
-                numFmtId);
-            XElement cellXfs = sXDoc
-                .Root
-                .Element(S.cellXfs);
-            if (cellXfs == null)
-            {
-                cellXfs = new XElement(S.cellXfs,
-                    new XAttribute(SSNoNamespace.count, 1),
-                    newXf);
-                return 0;
-            }
-            else
-            {
-                int currentCount = (int)cellXfs.Attribute(SSNoNamespace.count);
-                cellXfs.SetAttributeValue(SSNoNamespace.count, currentCount + 1);
-                cellXfs.Add(newXf);
-                return currentCount;
-            }
-        }
-
-        private static int GetFontId(XDocument sXDoc, CellDfn cell)
-        {
-            XElement fonts = sXDoc.Root.Element(S.fonts);
-            if (fonts == null)
-            {
-                fonts = new XElement(S.fonts,
-                    new XAttribute(SSNoNamespace.count, 1),
-                    new XElement(S.font,
-                        cell.Bold == true ? new XElement(S.b) : null,
-                        cell.Italic == true ? new XElement(S.i) : null));
-                sXDoc.Root.Add(fonts);
-                return 0;
-            }
-            XElement font = new XElement(S.font,
-                cell.Bold == true ? new XElement(S.b) : null,
-                cell.Italic == true ? new XElement(S.i) : null);
-            fonts.Add(font);
-            int count = (int)fonts.Attribute(SSNoNamespace.count);
-            fonts.SetAttributeValue(SSNoNamespace.count, count + 1);
-            return count;
-        }
-
-        private static int GetNumFmtId(XDocument sXDoc, string formatCode)
-        {
-            int xfNumber = 81;
-            while (true)
-            {
-                if (!sXDoc
-                    .Root
-                    .Elements(S.numFmts)
-                    .Elements(S.numFmt)
-                    .Any(nf => (int)nf.Attribute(SSNoNamespace.numFmtId) == xfNumber))
-                    break;
-                ++xfNumber;
-            }
-            XElement numFmts = sXDoc.Root.Element(S.numFmts);
-            if (numFmts == null)
-            {
-                numFmts = new XElement(S.numFmts,
-                    new XAttribute(SSNoNamespace.count, 1),
-                    new XElement(S.numFmt,
-                        new XAttribute(SSNoNamespace.numFmtId, xfNumber),
-                        new XAttribute(SSNoNamespace.formatCode, formatCode)));
-                sXDoc.Root.AddFirst(numFmts);
-                return xfNumber;
-            }
-            XElement numFmt = new XElement(S.numFmt,
-                new XAttribute(SSNoNamespace.numFmtId, xfNumber),
-                new XAttribute(SSNoNamespace.formatCode, formatCode));
-            numFmts.Add(numFmt);
-            return xfNumber;
-        }
-
-        private static bool CompareStyles(XDocument sXDoc, XElement xf, CellDfn cell)
-        {
-            bool matchFont = MatchFont(sXDoc, xf, cell);
-            bool matchAlignment = MatchAlignment(sXDoc, xf, cell);
-            bool matchFormat = MatchFormat(sXDoc, xf, cell);
-            return (matchFont && matchAlignment && matchFormat);
-        }
-
-        private static bool MatchFont(XDocument sXDoc, XElement xf, CellDfn cell)
-        {
-            if (((int?)xf.Attribute(SSNoNamespace.applyFont) == 0 ||
-                xf.Attribute(SSNoNamespace.applyFont) == null) &&
-                (cell.Bold == null || cell.Bold == false) &&
-                (cell.Italic == null || cell.Italic == false))
-                return true;
-            if (((int?)xf.Attribute(SSNoNamespace.applyFont) == 0 ||
-                xf.Attribute(SSNoNamespace.applyFont) == null) &&
-                (cell.Bold == true ||
-                 cell.Italic == true))
-                return false;
-            int fontId = (int)xf.Attribute(SSNoNamespace.fontId);
-            XElement font = sXDoc
-                .Root
-                .Element(S.fonts)
-                .Elements(S.font)
-                .ElementAt(fontId);
-            XElement fabFont = new XElement(S.font,
-                cell.Bold == true ? new XElement(S.b) : null,
-                cell.Italic == true ? new XElement(S.i) : null);
-            bool match = XNode.DeepEquals(font, fabFont);
-            return match;
-        }
-
-        private static bool MatchAlignment(XDocument sXDoc, XElement xf, CellDfn cell)
-        {
-            if ((int?)xf.Attribute(SSNoNamespace.applyAlignment) == 0 ||
-                (xf.Attribute(SSNoNamespace.applyAlignment) == null) &&
-                cell.HorizontalCellAlignment == null)
-                return true;
-            if (xf.Attribute(SSNoNamespace.applyAlignment) == null &&
-                cell.HorizontalCellAlignment != null)
-                return false;
-            string alignment = (string)xf.Element(S.alignment).Attribute(SSNoNamespace.horizontal);
-            bool match = alignment == cell.HorizontalCellAlignment.ToString().ToLower();
-            return match;
-        }
-
-        private static bool MatchFormat(XDocument sXDoc, XElement xf, CellDfn cell)
-        {
-            if ((int?)xf.Attribute(SSNoNamespace.applyNumberFormat) != 1 &&
-                cell.FormatCode == null)
-                return true;
-            if (xf.Attribute(SSNoNamespace.applyNumberFormat) == null &&
-                cell.FormatCode != null)
-                return false;
-            int numFmtId = (int)xf.Attribute(SSNoNamespace.numFmtId);
-            int? nfi = null;
-            if (cell.FormatCode != null)
-            {
-                if (CellDfn.StandardFormats.ContainsKey(cell.FormatCode))
-                    nfi = CellDfn.StandardFormats[cell.FormatCode];
-                if (nfi == numFmtId)
-                    return true;
-            }
-            XElement numFmts = sXDoc
-                .Root
-                .Element(S.numFmts);
-            if (numFmts == null)
-                return false;
-            XElement numFmt = numFmts
-                .Elements(S.numFmt)
-                .FirstOrDefault(numFmtElement =>
-                    (int)numFmtElement.Attribute(SSNoNamespace.numFmtId) == numFmtId);
-            if (numFmt == null)
-                return false;
-            string styleFormatCode = (string)numFmt.Attribute(SSNoNamespace.formatCode);
-            bool match = styleFormatCode == cell.FormatCode;
-            return match;
-        }
-
-        private static string _EmptyXlsx = @"UEsDBBQABgAIAAAAIQBi7p1oYQEAAJAEAAATAAgCW0Nvb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AGAAgAAAAhALVVMCP1AAAATAIAAAsAAAAAAAAAAAAAAAAAmgMAAF9y
-ZWxzLy5yZWxzUEsBAi0AFAAGAAgAAAAhAIE+lJf0AAAAugIAABoAAAAAAAAAAAAAAAAAwAYAAHhs
-L19yZWxzL3dvcmtib29rLnhtbC5yZWxzUEsBAi0AFAAGAAgAAAAhAASMvEhTAQAAJwIAAA8AAAAA
-AAAAAAAAAAAA9AgAAHhsL3dvcmtib29rLnhtbFBLAQItABQABgAIAAAAIQDQjLALfAAAAIEAAAAU
-AAAAAAAAAAAAAAAAAHQKAAB4bC9zaGFyZWRTdHJpbmdzLnhtbFBLAQItABQABgAIAAAAIQD7YqVt
-lAYAAKcbAAATAAAAAAAAAAAAAAAAACILAAB4bC90aGVtZS90aGVtZTEueG1sUEsBAi0AFAAGAAgA
-AAAhAJQ34e1HAgAA7AQAAA0AAAAAAAAAAAAAAAAA5xEAAHhsL3N0eWxlcy54bWxQSwECLQAUAAYA
-CAAAACEA5lWo42gBAACEAgAAGAAAAAAAAAAAAAAAAABZFAAAeGwvd29ya3NoZWV0cy9zaGVldDEu
-eG1sUEsBAi0AFAAGAAgAAAAhAJtkFtU+AQAAUQIAABEAAAAAAAAAAAAAAAAA9xUAAGRvY1Byb3Bz
-L2NvcmUueG1sUEsBAi0AFAAGAAgAAAAhAHREzCiJAQAAEQMAABAAAAAAAAAAAAAAAAAAbBgAAGRv
-Y1Byb3BzL2FwcC54bWxQSwUGAAAAAAoACgCAAgAAKxsAAAAA";
-
-    }
-
-    public class SpreadsheetWriterInternalException : Exception
-    {
-        public SpreadsheetWriterInternalException()
-            : base("Internal error - unexpected content in _EmptyXlsx.")
-        {
-        }
-    }
-
-    public class InvalidSheetNameException : Exception
-    {
-        public InvalidSheetNameException(string name)
-            : base(string.Format("The supplied name ({0}) is not a valid XLSX worksheet name.", name))
-        {
-        }
-    }
-}

+ 0 - 61
TEAMModelOS.SDK/Module/OpenXmlTool/StronglyTypedBlock.cs

@@ -1,61 +0,0 @@
-// 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 DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    /// <summary>
-    /// Provides an elegant way of wrapping a set of invocations of the strongly typed 
-    /// classes provided by the Open XML SDK) in a using statement that demarcates those
-    /// invokations as one "block" before and after which the PowerTools can be used safely.
-    /// </summary>
-    /// <remarks>
-    /// <para>
-    /// This class lends itself to scenarios where the PowerTools and Linq-to-XML are used as
-    /// the primary API for working with Open XML elements, next to the strongly typed classes
-    /// provided by the Open XML SDK. In these scenarios, the class would be used as follows:
-    /// </para>
-    /// <code>
-    ///     [Your code using the PowerTools]
-    /// 
-    ///     using (new NonPowerToolsBlock(wordprocessingDocument))
-    ///     {
-    ///         [Your code using the strongly typed classes]
-    ///     }
-    /// 
-    ///    [Your code using the PowerTools]
-    /// </code>
-    /// <para>
-    /// Upon creation, instances of this class will invoke the
-    /// <see cref="PowerToolsBlockExtensions.EndPowerToolsBlock"/> method on the package
-    /// to begin the block. Upon disposal, instances of this class will call the
-    /// <see cref="PowerToolsBlockExtensions.BeginPowerToolsBlock"/> method on the package
-    /// to end the block.
-    /// </para>
-    /// </remarks>
-    /// <seealso cref="PowerToolsBlock"/>
-    /// <seealso cref="PowerToolsBlockExtensions.BeginPowerToolsBlock"/>
-    /// <seealso cref="PowerToolsBlockExtensions.EndPowerToolsBlock"/>
-    public class StronglyTypedBlock : IDisposable
-    {
-        private OpenXmlPackage _package;
-
-        public StronglyTypedBlock(OpenXmlPackage package)
-        {
-            if (package == null) throw new ArgumentNullException("package");
-
-            _package = package;
-            _package.EndPowerToolsBlock();
-        }
-
-        public void Dispose()
-        {
-            if (_package == null) return;
-
-            _package.BeginPowerToolsBlock();
-            _package = null;
-        }
-    }
-}

+ 0 - 72
TEAMModelOS.SDK/Module/OpenXmlTool/TestUtil.cs

@@ -1,72 +0,0 @@
-// 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.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace OpenXmlPowerTools
-{
-    public class TestUtil
-    {
-        private static bool? s_DeleteTempFiles = null;
-
-        public static bool DeleteTempFiles
-        {
-            get
-            {
-                if (s_DeleteTempFiles != null)
-                    return (bool)s_DeleteTempFiles;
-                FileInfo donotdelete = new FileInfo("donotdelete.txt");
-                s_DeleteTempFiles = !donotdelete.Exists;
-                return (bool)s_DeleteTempFiles;
-            }
-        }
-
-        private static DirectoryInfo s_TempDir = null;
-        public static DirectoryInfo TempDir
-        {
-            get
-            {
-                if (s_TempDir != null)
-                    return s_TempDir;
-                else
-                {
-                    var now = DateTime.Now;
-                    var tempDirName = String.Format("Test-{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);
-                    s_TempDir = new DirectoryInfo(Path.Combine(".", tempDirName));
-                    s_TempDir.Create();
-                    return s_TempDir;
-                }
-            }
-        }
-
-        public static void NotePad(string str)
-        {
-            var guidName = Guid.NewGuid().ToString().Replace("-", "") + ".txt";
-            var fi = new FileInfo(Path.Combine(TempDir.FullName, guidName));
-            File.WriteAllText(fi.FullName, str);
-            var notepadExe = new FileInfo(@"C:\Program Files (x86)\Notepad++\notepad++.exe");
-            if (!notepadExe.Exists)
-                notepadExe = new FileInfo(@"C:\Program Files\Notepad++\notepad++.exe");
-            if (!notepadExe.Exists)
-                notepadExe = new FileInfo(@"C:\Windows\System32\notepad.exe");
-            ExecutableRunner.RunExecutable(notepadExe.FullName, fi.FullName, TempDir.FullName);
-        }
-
-        public static void KDiff3(FileInfo oldFi, FileInfo newFi)
-        {
-            var kdiffExe = new FileInfo(@"C:\Program Files (x86)\KDiff3\kdiff3.exe");
-            var result = ExecutableRunner.RunExecutable(kdiffExe.FullName, oldFi.FullName + " " + newFi.FullName, TempDir.FullName);
-        }
-
-        public static void Explorer(DirectoryInfo di)
-        {
-            Process.Start(di.FullName);
-        }
-    }
-}

+ 0 - 428
TEAMModelOS.SDK/Module/OpenXmlTool/TextReplacer.cs

@@ -1,428 +0,0 @@
-// 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.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Xml;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public partial class WmlDocument : OpenXmlPowerToolsDocument
-    {
-        public WmlDocument SearchAndReplace(string search, string replace, bool matchCase)
-        {
-            return TextReplacer.SearchAndReplace(this, search, replace, matchCase);
-        }
-    }
-
-    public partial class PmlDocument : OpenXmlPowerToolsDocument
-    {
-        public PmlDocument SearchAndReplace(string search, string replace, bool matchCase)
-        {
-            return TextReplacer.SearchAndReplace(this, search, replace, matchCase);
-        }
-    }
-
-    public class TextReplacer
-    {
-        private class MatchSemaphore
-        {
-            public int MatchId;
-            public MatchSemaphore(int matchId)
-            {
-                MatchId = matchId;
-            }
-        }
-
-        private static XObject CloneWithAnnotation(XNode node)
-        {
-            XElement element = node as XElement;
-            if (element != null)
-            {
-                XElement newElement = new XElement(element.Name,
-                    element.Attributes(),
-                    element.Nodes().Select(n => CloneWithAnnotation(n)));
-                if (element.Annotation<MatchSemaphore>() != null)
-                    newElement.AddAnnotation(element.Annotation<MatchSemaphore>());
-            }
-            return node;
-        }
-
-        private static object WmlSearchAndReplaceTransform(XNode node,
-            string search, string replace, bool matchCase)
-        {
-            XElement element = node as XElement;
-            if (element != null)
-            {
-                if (element.Name == W.p)
-                {
-                    string contents = element.Descendants(W.t).Select(t => (string)t).StringConcatenate();
-                    if (contents.Contains(search) ||
-                        (!matchCase && contents.ToUpper().Contains(search.ToUpper())))
-                    {
-                        XElement paragraphWithSplitRuns = new XElement(W.p,
-                            element.Attributes(),
-                            element.Nodes().Select(n => WmlSearchAndReplaceTransform(n, search,
-                                replace, matchCase)));
-                        XElement[] subRunArray = paragraphWithSplitRuns
-                            .Elements(W.r)
-                            .Where(e => {
-                                XElement subRunElement = e.Elements().FirstOrDefault(el => el.Name != W.rPr);
-                                if (subRunElement == null)
-                                    return false;
-                                return W.SubRunLevelContent.Contains(subRunElement.Name);
-                            })
-                            .ToArray();
-                        int paragraphChildrenCount = subRunArray.Length;
-                        int matchId = 1;
-                        foreach (var pc in subRunArray
-                            .Take(paragraphChildrenCount - (search.Length - 1))
-                            .Select((c, i) => new { Child = c, Index = i, }))
-                        {
-                            var subSequence = subRunArray.SequenceAt(pc.Index).Take(search.Length);
-                            var zipped = subSequence.PtZip(search, (pcp, c) => new
-                            {
-                                ParagraphChildProjection = pcp,
-                                CharacterToCompare = c,
-                            });
-                            bool dontMatch = zipped.Any(z => {
-                                if (z.ParagraphChildProjection.Annotation<MatchSemaphore>() != null)
-                                    return true;
-                                bool b;
-                                if (matchCase)
-                                    b = z.ParagraphChildProjection.Value != z.CharacterToCompare.ToString();
-                                else
-                                    b = z.ParagraphChildProjection.Value.ToUpper() != z.CharacterToCompare.ToString().ToUpper();
-                                return b;
-                            });
-                            bool match = !dontMatch;
-                            if (match)
-                            {
-                                foreach (var item in subSequence)
-                                    item.AddAnnotation(new MatchSemaphore(matchId));
-                                ++matchId;
-                            }
-                        }
-
-                        // The following code is locally impure, as this is the most expressive way to write it.
-                        XElement paragraphWithReplacedRuns = (XElement)CloneWithAnnotation(paragraphWithSplitRuns);
-                        for (int id = 1; id < matchId; ++id)
-                        {
-                            List<XElement> elementsToReplace = paragraphWithReplacedRuns
-                                .Elements()
-                                .Where(e => {
-                                    var sem = e.Annotation<MatchSemaphore>();
-                                    if (sem == null)
-                                        return false;
-                                    return sem.MatchId == id;
-                                })
-                                .ToList();
-                            elementsToReplace.First().AddBeforeSelf(
-                                new XElement(W.r,
-                                    elementsToReplace.First().Elements(W.rPr),
-                                    new XElement(W.t, replace)));
-                            elementsToReplace.Remove();
-                        }
-                        var groupedAdjacentRunsWithIdenticalFormatting =
-                            paragraphWithReplacedRuns
-                            .Elements()
-                            .GroupAdjacent(ce =>
-                            {
-                                if (ce.Name != W.r)
-                                    return "DontConsolidate";
-                                if (ce.Elements().Where(e => e.Name != W.rPr).Count() != 1 ||
-                                    ce.Element(W.t) == null)
-                                    return "DontConsolidate";
-                                if (ce.Element(W.rPr) == null)
-                                    return "";
-                                return ce.Element(W.rPr).ToString(SaveOptions.None);
-                            });
-                        XElement paragraphWithConsolidatedRuns = new XElement(W.p,
-                            groupedAdjacentRunsWithIdenticalFormatting.Select(g =>
-                                {
-                                    if (g.Key == "DontConsolidate")
-                                        return (object)g;
-                                    string textValue = g.Select(r => r.Element(W.t).Value).StringConcatenate();
-                                    XAttribute xs = null;
-                                    if (textValue[0] == ' ' || textValue[textValue.Length - 1] == ' ')
-                                        xs = new XAttribute(XNamespace.Xml + "space", "preserve");
-                                    return new XElement(W.r,
-                                        g.First().Elements(W.rPr),
-                                        new XElement(W.t, xs, textValue));
-                                }));
-                        return paragraphWithConsolidatedRuns;
-                    }
-                    return element;
-                }
-                if (element.Name == W.r && element.Elements(W.t).Any())
-                {
-                    var collectionOfRuns = element.Elements()
-                        .Where(e => e.Name != W.rPr)
-                        .Select(e =>
-                            {
-                                if (e.Name == W.t)
-                                {
-                                    string s = (string)e;
-                                    IEnumerable<XElement> collectionOfSubRuns = s.Select(c =>
-                                    {
-                                        XElement newRun = new XElement(W.r,
-                                            element.Elements(W.rPr),
-                                            new XElement(W.t,
-                                                c == ' ' ?
-                                                new XAttribute(XNamespace.Xml + "space", "preserve") :
-                                                null, c));
-                                        return newRun;
-                                    });
-                                    return (object)collectionOfSubRuns;
-                                }
-                                else
-                                {
-                                    XElement newRun = new XElement(W.r,
-                                        element.Elements(W.rPr),
-                                        e);
-                                    return newRun;
-                                }
-                            });
-                    return collectionOfRuns;
-                }
-                return new XElement(element.Name,
-                    element.Attributes(),
-                    element.Nodes().Select(n => WmlSearchAndReplaceTransform(n,
-                        search, replace, matchCase)));
-            }
-            return node;
-        }
-
-        private static void WmlSearchAndReplaceInXDocument(XDocument xDocument, string search,
-            string replace, bool matchCase)
-        {
-            XElement newRoot = (XElement)WmlSearchAndReplaceTransform(xDocument.Root,
-                search, replace, matchCase);
-            xDocument.Elements().First().ReplaceWith(newRoot);
-        }
-
-        public static WmlDocument SearchAndReplace(WmlDocument doc, string search, string replace, bool matchCase)
-        {
-            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
-            {
-                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
-                {
-                    SearchAndReplace(document, search, replace, matchCase);
-                }
-                return streamDoc.GetModifiedWmlDocument();
-            }
-        }
-
-        public static void SearchAndReplace(WordprocessingDocument wordDoc, string search,
-            string replace, bool matchCase)
-        {
-            if (RevisionAccepter.HasTrackedRevisions(wordDoc))
-                throw new InvalidDataException(
-                    "Search and replace will not work with documents " +
-                    "that contain revision tracking.");
-            XDocument xDoc;
-            xDoc = wordDoc.MainDocumentPart.DocumentSettingsPart.GetXDocument();
-            if (xDoc.Descendants(W.trackRevisions).Any())
-                throw new InvalidDataException("Revision tracking is turned on for document.");
-
-            xDoc = wordDoc.MainDocumentPart.GetXDocument();
-            WmlSearchAndReplaceInXDocument(xDoc, search, replace, matchCase);
-            wordDoc.MainDocumentPart.PutXDocument();
-            foreach (var part in wordDoc.MainDocumentPart.HeaderParts)
-            {
-                xDoc = part.GetXDocument();
-                WmlSearchAndReplaceInXDocument(xDoc, search, replace, matchCase);
-                part.PutXDocument();
-            }
-            foreach (var part in wordDoc.MainDocumentPart.FooterParts)
-            {
-                xDoc = part.GetXDocument();
-                WmlSearchAndReplaceInXDocument(xDoc, search, replace, matchCase);
-                part.PutXDocument();
-            }
-            if (wordDoc.MainDocumentPart.EndnotesPart != null)
-            {
-                xDoc = wordDoc.MainDocumentPart.EndnotesPart.GetXDocument();
-                WmlSearchAndReplaceInXDocument(xDoc, search, replace, matchCase);
-                wordDoc.MainDocumentPart.EndnotesPart.PutXDocument();
-            }
-            if (wordDoc.MainDocumentPart.FootnotesPart != null)
-            {
-                xDoc = wordDoc.MainDocumentPart.FootnotesPart.GetXDocument();
-                WmlSearchAndReplaceInXDocument(xDoc, search, replace, matchCase);
-                wordDoc.MainDocumentPart.FootnotesPart.PutXDocument();
-            }
-        }
-
-        private static object PmlReplaceTextTransform(XNode node, string search, string replace,
-            bool matchCase)
-        {
-            XElement element = node as XElement;
-            if (element != null)
-            {
-                if (element.Name == A.p)
-                {
-                    string contents = element.Descendants(A.t).Select(t => (string)t).StringConcatenate();
-                    if (contents.Contains(search) ||
-                        (!matchCase && contents.ToUpper().Contains(search.ToUpper())))
-                    {
-                        XElement paragraphWithSplitRuns = new XElement(A.p,
-                            element.Attributes(),
-                            element.Nodes().Select(n => PmlReplaceTextTransform(n, search,
-                                replace, matchCase)));
-                        XElement[] subRunArray = paragraphWithSplitRuns
-                            .Elements(A.r)
-                            .Where(e =>
-                            {
-                                XElement subRunElement = e.Elements().FirstOrDefault(el => el.Name != A.rPr);
-                                if (subRunElement == null)
-                                    return false;
-                                return subRunElement.Name == A.t;
-                            })
-                            .ToArray();
-                        int paragraphChildrenCount = subRunArray.Length;
-                        int matchId = 1;
-                        foreach (var pc in subRunArray
-                            .Take(paragraphChildrenCount - (search.Length - 1))
-                            .Select((c, i) => new { Child = c, Index = i, }))
-                        {
-                            var subSequence = subRunArray.SequenceAt(pc.Index).Take(search.Length);
-                            var zipped = subSequence.PtZip(search, (pcp, c) => new
-                            {
-                                ParagraphChildProjection = pcp,
-                                CharacterToCompare = c,
-                            });
-                            bool dontMatch = zipped.Any(z =>
-                            {
-                                if (z.ParagraphChildProjection.Annotation<MatchSemaphore>() != null)
-                                    return true;
-                                bool b;
-                                if (matchCase)
-                                    b = z.ParagraphChildProjection.Value != z.CharacterToCompare.ToString();
-                                else
-                                    b = z.ParagraphChildProjection.Value.ToUpper() != z.CharacterToCompare.ToString().ToUpper();
-                                return b;
-                            });
-                            bool match = !dontMatch;
-                            if (match)
-                            {
-                                foreach (var item in subSequence)
-                                    item.AddAnnotation(new MatchSemaphore(matchId));
-                                ++matchId;
-                            }
-                        }
-
-                        // The following code is locally impure, as this is the most expressive way to write it.
-                        XElement paragraphWithReplacedRuns = (XElement)CloneWithAnnotation(paragraphWithSplitRuns);
-                        for (int id = 1; id < matchId; ++id)
-                        {
-                            List<XElement> elementsToReplace = paragraphWithReplacedRuns
-                                .Elements()
-                                .Where(e =>
-                                {
-                                    var sem = e.Annotation<MatchSemaphore>();
-                                    if (sem == null)
-                                        return false;
-                                    return sem.MatchId == id;
-                                })
-                                .ToList();
-                            elementsToReplace.First().AddBeforeSelf(
-                                new XElement(A.r,
-                                    elementsToReplace.First().Elements(A.rPr),
-                                    new XElement(A.t, replace)));
-                            elementsToReplace.Remove();
-                        }
-
-                        var groupedAdjacentRunsWithIdenticalFormatting =
-                            paragraphWithReplacedRuns
-                            .Elements()
-                            .GroupAdjacent(ce =>
-                            {
-                                if (ce.Name != A.r)
-                                    return "DontConsolidate";
-                                if (ce.Elements().Where(e => e.Name != A.rPr).Count() != 1 ||
-                                    ce.Element(A.t) == null)
-                                    return "DontConsolidate";
-                                if (ce.Element(A.rPr) == null)
-                                    return "";
-                                return ce.Element(A.rPr).ToString(SaveOptions.None);
-                            });
-                        XElement paragraphWithConsolidatedRuns = new XElement(A.p,
-                            groupedAdjacentRunsWithIdenticalFormatting.Select(g =>
-                            {
-                                if (g.Key == "DontConsolidate")
-                                    return (object)g;
-                                string textValue = g.Select(r => r.Element(A.t).Value).StringConcatenate();
-                                return new XElement(A.r,
-                                    g.First().Elements(A.rPr),
-                                    new XElement(A.t, textValue));
-                            }));
-                        return paragraphWithConsolidatedRuns;
-                    }
-                }
-                if (element.Name == A.r && element.Elements(A.t).Any())
-                {
-                    var collectionOfRuns = element.Elements()
-                        .Where(e => e.Name != A.rPr)
-                        .Select(e =>
-                        {
-                            if (e.Name == A.t)
-                            {
-                                string s = (string)e;
-                                IEnumerable<XElement> collectionOfSubRuns = s.Select(c =>
-                                {
-                                    XElement newRun = new XElement(A.r,
-                                        element.Elements(A.rPr),
-                                        new XElement(A.t, c));
-                                    return newRun;
-                                });
-                                return (object)collectionOfSubRuns;
-                            }
-                            else
-                            {
-                                XElement newRun = new XElement(A.r,
-                                    element.Elements(A.rPr),
-                                    e);
-                                return newRun;
-                            }
-                        });
-                    return collectionOfRuns;
-                }
-                return new XElement(element.Name,
-                    element.Attributes(),
-                    element.Nodes().Select(n => PmlReplaceTextTransform(n, search, replace, matchCase)));
-            }
-            return node;
-        }
-
-        public static PmlDocument SearchAndReplace(PmlDocument doc, string search, string replace, bool matchCase)
-        {
-            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
-            {
-                using (PresentationDocument document = streamDoc.GetPresentationDocument())
-                {
-                    SearchAndReplace(document, search, replace, matchCase);
-                }
-                return streamDoc.GetModifiedPmlDocument();
-            }
-        }
-
-        public static void SearchAndReplace(PresentationDocument pDoc, string search,
-            string replace, bool matchCase)
-        {
-            PresentationPart presentationPart = pDoc.PresentationPart;
-            foreach (var slidePart in presentationPart.SlideParts)
-            {
-                XDocument slideXDoc = slidePart.GetXDocument();
-                XElement root = slideXDoc.Root;
-                XElement newRoot = (XElement)PmlReplaceTextTransform(root, search, replace, matchCase);
-                slidePart.PutXDocument(new XDocument(newRoot));
-            }
-        }
-    }
-}

+ 0 - 337
TEAMModelOS.SDK/Module/OpenXmlTool/UnicodeMapper.cs

@@ -1,337 +0,0 @@
-// Copyright (c) Microsoft. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-/***************************************************************************
-
-Copyright (c) Microsoft Corporation 2016.
-
-This code is licensed using the Microsoft Public License (Ms-PL).  The text of the license can be found here:
-
-http://www.microsoft.com/resources/sharedsource/licensingbasics/publiclicense.mspx
-
-Developer: Thomas Barnekow
-Email: thomas@barnekow.info
-
-***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Xml.Linq;
-
-namespace OpenXmlPowerTools
-{
-    public class UnicodeMapper
-    {
-        // Unicode character values.
-        public static readonly char StartOfHeading = '\u0001';
-        public static readonly char HorizontalTabulation = '\u0009';
-        public static readonly char LineFeed = '\u000A';
-        public static readonly char FormFeed = '\u000C';
-        public static readonly char CarriageReturn = '\u000D';
-        public static readonly char SoftHyphen = '\u00AD';
-        public static readonly char NonBreakingHyphen = '\u2011';
-
-        // Unicode area boundaries.
-        public static readonly char StartOfPrivateUseArea = '\uE000';
-        public static readonly char StartOfSymbolArea = '\uF000';
-        public static readonly char EndOfPrivateUseArea = '\uF8FF';
-
-        // Dictionaries for w:sym stringification.
-        private static readonly Dictionary<string, char> SymStringToUnicodeCharDictionary =
-            new Dictionary<string, char>();
-
-        private static readonly Dictionary<char, XElement> UnicodeCharToSymDictionary =
-            new Dictionary<char, XElement>();
-
-        // Represents the Unicode value that was last used to map an actual character
-        // onto a special value in the private use area, which starts at U+E000.
-        // In Open XML, U+F000 is added to the actual Unicode values, so we should be
-        // well outside that range and would have to map 4096 different characters
-        // to get into the area starting at U+F000.
-        private static char _lastUnicodeChar = StartOfPrivateUseArea;
-
-        /// <summary>
-        /// Stringify an Open XML run, turning (a) w:t, w:br, w:cr, w:noBreakHyphen,
-        /// w:softHyphen,  w:sym, and w:tab into their corresponding Unicode strings
-        /// and (b) everything else into U+0001.
-        /// </summary>
-        /// <param name="element">An Open XML run or run child element.</param>
-        /// <returns>The corresponding Unicode value or U+0001.</returns>
-        public static string RunToString(XElement element)
-        {
-            if (element.Name == W.r && (element.Parent == null || element.Parent.Name != W.del))
-                return element.Elements().Select(RunToString).StringConcatenate();
-
-            // We need to ignore run properties.
-            if (element.Name == W.rPr)
-                return string.Empty;
-
-            // For w:t elements, we obviously want the element's value.
-            if (element.Name == W.t)
-                return (string) element;
-
-            // Turn elements representing special characters into their corresponding
-            // unicode characters.
-            if (element.Name == W.br)
-            {
-                XAttribute typeAttribute = element.Attribute(W.type);
-                string type = typeAttribute != null ? typeAttribute.Value : null;
-                if (type == null || type == "textWrapping")
-                    return CarriageReturn.ToString();
-                if (type == "page")
-                    return FormFeed.ToString();
-            }
-
-            if (element.Name == W.cr)
-                return CarriageReturn.ToString();
-            if (element.Name == W.noBreakHyphen)
-                return NonBreakingHyphen.ToString();
-            if (element.Name == W.softHyphen)
-                return SoftHyphen.ToString();
-            if (element.Name == W.tab)
-                return HorizontalTabulation.ToString();
-
-            if (element.Name == W.fldChar)
-            {
-                var fldCharType = element.Attributes(W.fldCharType).Select(a => a.Value).FirstOrDefault();
-                switch (fldCharType)
-                {
-                    case "begin":
-                        return "{";
-                    case "end":
-                        return "}";
-                    default:
-                        return "_";
-                }
-            }
-
-            if (element.Name == W.instrText)
-                return "_";
-
-            // Turn w:sym elements into Unicode character values. A w:char attribute
-            // value can be stored (a) directly in its Unicode character value from
-            // the font glyph or (b) in a Unicode character value created by adding
-            // U+F000 to the character value, thereby shifting the value into the
-            // Unicode private use area.
-            if (element.Name == W.sym)
-                return SymToChar(element).ToString();
-
-            // Elements we don't recognize will be turned into a character that
-            // doesn't typically appear in documents.
-            return StartOfHeading.ToString();
-        }
-
-        /// <summary>
-        /// Translate a symbol into a Unicode character, using the specified w:font attribute
-        /// value and unicode value (represented by the w:sym element's w:char attribute),
-        /// using a substitute value for the actual Unicode value if the same Unicode value
-        /// is already used in conjunction with a different w:font attribute value.
-        ///
-        /// Add U+F000 to the Unicode value if the specified value is less than U+1000, which
-        /// shifts the value into the Unicode private use area (which is also done by MS Word).
-        /// </summary>
-        /// <remarks>
-        /// For w:sym elements, the w:char attribute value is typically greater than "F000",
-        /// because U+F000 is added to the actual Unicode value to shift the value into
-        /// the Unicode private use area.
-        /// </remarks>
-        /// <param name="fontAttributeValue">The w:font attribute value, e.g., "Wingdings".</param>
-        /// <param name="unicodeValue">The unicode value.</param>
-        /// <returns>The Unicode character used to represent the symbol.</returns>
-        public static char SymToChar(string fontAttributeValue, char unicodeValue)
-        {
-            return SymToChar(fontAttributeValue, (int) unicodeValue);
-        }
-
-        /// <summary>
-        /// Translate a symbol into a Unicode character, using the specified w:font attribute
-        /// value and unicode value (represented by the w:sym element's w:char attribute),
-        /// using a substitute value for the actual Unicode value if the same Unicode value
-        /// is already used in conjunction with a different w:font attribute value.
-        ///
-        /// Add U+F000 to the Unicode value if the specified value is less than U+1000, which
-        /// shifts the value into the Unicode private use area (which is also done by MS Word).
-        /// </summary>
-        /// <remarks>
-        /// For w:sym elements, the w:char attribute value is typically greater than "F000",
-        /// because U+F000 is added to the actual Unicode value to shift the value into
-        /// the Unicode private use area.
-        /// </remarks>
-        /// <param name="fontAttributeValue">The w:font attribute value, e.g., "Wingdings".</param>
-        /// <param name="unicodeValue">The unicode value.</param>
-        /// <returns>The Unicode character used to represent the symbol.</returns>
-        public static char SymToChar(string fontAttributeValue, int unicodeValue)
-        {
-            int effectiveUnicodeValue = unicodeValue < 0x1000 ? 0xF000 + unicodeValue : unicodeValue;
-            return SymToChar(fontAttributeValue, effectiveUnicodeValue.ToString("X4"));
-        }
-
-        /// <summary>
-        /// Translate a symbol into a Unicode character, using the specified w:font and
-        /// w:char attribute values, using a substitute value for the actual Unicode
-        /// value if the same Unicode value is already used in conjunction with a different
-        /// w:font attribute value.
-        ///
-        /// Do not alter the w:char attribute value.
-        /// </summary>
-        /// <remarks>
-        /// For w:sym elements, the w:char attribute value is typically greater than "F000",
-        /// because U+F000 is added to the actual Unicode value to shift the value into
-        /// the Unicode private use area.
-        /// </remarks>
-        /// <param name="fontAttributeValue">The w:font attribute value, e.g., "Wingdings".</param>
-        /// <param name="charAttributeValue">The w:char attribute value, e.g., "F028".</param>
-        /// <returns>The Unicode character used to represent the symbol.</returns>
-        public static char SymToChar(string fontAttributeValue, string charAttributeValue)
-        {
-            if (string.IsNullOrEmpty(fontAttributeValue))
-                throw new ArgumentException("Argument is null or empty.", "fontAttributeValue");
-            if (string.IsNullOrEmpty(charAttributeValue))
-                throw new ArgumentException("Argument is null or empty.", "charAttributeValue");
-
-            return SymToChar(new XElement(W.sym,
-                new XAttribute(W.font, fontAttributeValue),
-                new XAttribute(W._char, charAttributeValue),
-                new XAttribute(XNamespace.Xmlns + "w", W.w)));
-        }
-
-        /// <summary>
-        /// Represent a w:sym element as a Unicode value, mapping the Unicode value
-        /// specified in the w:char attribute to a substitute value to be able to
-        /// use a Unicode value in conjunction with different fonts.
-        /// </summary>
-        /// <param name="sym">The w:sym element to be stringified.</param>
-        /// <returns>A single-character Unicode string representing the w:sym element.</returns>
-        public static char SymToChar(XElement sym)
-        {
-            if (sym == null)
-                throw new ArgumentNullException("sym");
-            if (sym.Name != W.sym)
-                throw new ArgumentException(string.Format("Not a w:sym: {0}", sym.Name), "sym");
-
-            XAttribute fontAttribute = sym.Attribute(W.font);
-            string fontAttributeValue = fontAttribute != null ? fontAttribute.Value : null;
-            if (fontAttributeValue == null)
-                throw new ArgumentException("w:sym element has no w:font attribute.", "sym");
-
-            XAttribute charAttribute = sym.Attribute(W._char);
-            string charAttributeValue = charAttribute != null ? charAttribute.Value : null;
-            if (charAttributeValue == null)
-                throw new ArgumentException("w:sym element has no w:char attribute.", "sym");
-
-            // Return Unicode value if it is in the dictionary.
-            var standardizedSym = new XElement(W.sym,
-                new XAttribute(W.font, fontAttributeValue),
-                new XAttribute(W._char, charAttributeValue),
-                new XAttribute(XNamespace.Xmlns + "w", W.w));
-            string standardizedSymString = standardizedSym.ToString(SaveOptions.None);
-            if (SymStringToUnicodeCharDictionary.ContainsKey(standardizedSymString))
-                return SymStringToUnicodeCharDictionary[standardizedSymString];
-
-            // Determine Unicode value to be used to represent the current w:sym element.
-            // Use the actual Unicode value if it has not yet been used with another font.
-            // Otherwise, create a special Unicode value in the private use area to represent
-            // the current w:sym element.
-            var unicodeChar = (char) Convert.ToInt32(charAttributeValue, 16);
-            if (UnicodeCharToSymDictionary.ContainsKey(unicodeChar))
-                unicodeChar = ++_lastUnicodeChar;
-
-            SymStringToUnicodeCharDictionary.Add(standardizedSymString, unicodeChar);
-            UnicodeCharToSymDictionary.Add(unicodeChar, standardizedSym);
-            return unicodeChar;
-        }
-
-        /// <summary>
-        /// Turn the specified text value into a list of runs with coalesced text elements.
-        /// Each run will have the specified run properties.
-        /// </summary>
-        /// <param name="textValue">The text value to transform.</param>
-        /// <param name="runProperties">The run properties to apply.</param>
-        /// <returns>A list of runs representing the text value.</returns>
-        public static List<XElement> StringToCoalescedRunList(string textValue, XElement runProperties)
-        {
-            return textValue
-                .Select(CharToRunChild)
-                .GroupAdjacent(e => e.Name == W.t)
-                .SelectMany(grouping => grouping.Key
-                    ? StringToSingleRunList(grouping.Select(t => (string) t).StringConcatenate(), runProperties)
-                    : grouping.Select(e => new XElement(W.r, runProperties, e)))
-                .ToList();
-        }
-
-        /// <summary>
-        /// Turn the specified text value into a list consisting of a single run having one
-        /// text element with that text value. The run will have the specified run properties.
-        /// </summary>
-        /// <param name="textValue">The text value to transform.</param>
-        /// <param name="runProperties">The run properties to apply.</param>
-        /// <returns>A list with a single run.</returns>
-        public static IEnumerable<XElement> StringToSingleRunList(string textValue, XElement runProperties)
-        {
-            var run = new XElement(W.r,
-                runProperties,
-                new XElement(W.t, XmlUtil.GetXmlSpaceAttribute(textValue), textValue));
-            return new List<XElement> { run };
-        }
-
-        /// <summary>
-        /// Turn the specified text value into a list of runs, each having the specified
-        /// run properties.
-        /// </summary>
-        /// <param name="textValue">The text value to transform.</param>
-        /// <param name="runProperties">The run properties to apply.</param>
-        /// <returns>A list of runs representing the text value.</returns>
-        public static List<XElement> StringToRunList(string textValue, XElement runProperties)
-        {
-            return textValue.Select(character => CharToRun(character, runProperties)).ToList();
-        }
-
-        /// <summary>
-        /// Create a w:r element from the specified character, which will be turned
-        /// into a corresponding Open XML element (e.g., w:t, w:br, w:tab).
-        /// </summary>
-        /// <param name="character">The character.</param>
-        /// <param name="runProperties">The w:rPr element to be added to the w:r element.</param>
-        /// <returns>The w:r element.</returns>
-        public static XElement CharToRun(char character, XElement runProperties)
-        {
-            return new XElement(W.r, runProperties, CharToRunChild(character));
-        }
-
-        /// <summary>
-        /// Create an Open XML element (e.g., w:t, w:br, w:tab) from the specified
-        /// character.
-        /// </summary>
-        /// <param name="character">The character.</param>
-        /// <returns>The Open XML element or null, if the character equals <see cref="StartOfHeading" /> (U+0001).</returns>
-        public static XElement CharToRunChild(char character)
-        {
-            // Ignore the special character that represents the Open XML elements we
-            // wanted to ignore.
-            if (character == StartOfHeading)
-                return null;
-
-            // Translate special characters into their corresponding Open XML elements.
-            // Turn a Carriage Return into an empty w:br element, regardless of whether
-            // the former was created from an equivalent w:cr element.
-            if (character == CarriageReturn)
-                return new XElement(W.br);
-            if (character == FormFeed)
-                return new XElement(W.br, new XAttribute(W.type, "page"));
-            if (character == HorizontalTabulation)
-                return new XElement(W.tab);
-            if (character == NonBreakingHyphen)
-                return new XElement(W.noBreakHyphen);
-            if (character == SoftHyphen)
-                return new XElement(W.softHyphen);
-
-            // Translate symbol characters into their corresponding w:sym elements.
-            if (UnicodeCharToSymDictionary.ContainsKey(character))
-                return UnicodeCharToSymDictionary[character];
-
-            // Turn "normal" characters into text elements.
-            return new XElement(W.t, XmlUtil.GetXmlSpaceAttribute(character), character);
-        }
-    }
-}

+ 0 - 106
TEAMModelOS.SDK/Module/OpenXmlTool/WmlDocument.cs

@@ -1,106 +0,0 @@
-// 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.Generic;
-using System.IO;
-using System.IO.Packaging;
-using System.Linq;
-using System.Text;
-using System.Xml;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-
-namespace OpenXmlPowerTools
-{
-    public class PtMainDocumentPart : XElement
-    {
-        private WmlDocument ParentWmlDocument;
-
-        public PtWordprocessingCommentsPart WordprocessingCommentsPart
-        {
-            get
-            {
-                using (MemoryStream ms = new MemoryStream(ParentWmlDocument.DocumentByteArray))
-                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, false))
-                {
-                    WordprocessingCommentsPart commentsPart = wDoc.MainDocumentPart.WordprocessingCommentsPart;
-                    if (commentsPart == null)
-                        return null;
-                    XElement partElement = commentsPart.GetXDocument().Root;
-                    var childNodes = partElement.Nodes().ToList();
-                    foreach (var item in childNodes)
-                        item.Remove();
-                    return new PtWordprocessingCommentsPart(this.ParentWmlDocument, commentsPart.Uri, partElement.Name, partElement.Attributes(), childNodes);
-                }
-            }
-        }
-
-        public PtMainDocumentPart(WmlDocument wmlDocument, Uri uri, XName name, params object[] values)
-            : base(name, values)
-        {
-            ParentWmlDocument = wmlDocument;
-            this.Add(
-                new XAttribute(PtOpenXml.Uri, uri),
-                new XAttribute(XNamespace.Xmlns + "pt", PtOpenXml.pt)
-            );
-        }
-    }
-
-    public class PtWordprocessingCommentsPart : XElement
-    {
-        private WmlDocument ParentWmlDocument;
-
-        public PtWordprocessingCommentsPart(WmlDocument wmlDocument, Uri uri, XName name, params object[] values)
-            : base(name, values)
-        {
-            ParentWmlDocument = wmlDocument;
-            this.Add(
-                new XAttribute(PtOpenXml.Uri, uri),
-                new XAttribute(XNamespace.Xmlns + "pt", PtOpenXml.pt)
-            );
-        }
-    }
-
-    public partial class WmlDocument
-    {
-        public PtMainDocumentPart MainDocumentPart
-        {
-            get
-            {
-                using (MemoryStream ms = new MemoryStream(this.DocumentByteArray))
-                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, false))
-                {
-                    XElement partElement = wDoc.MainDocumentPart.GetXDocument().Root;
-                    var childNodes = partElement.Nodes().ToList();
-                    foreach (var item in childNodes)
-                        item.Remove();
-                    return new PtMainDocumentPart(this, wDoc.MainDocumentPart.Uri, partElement.Name, partElement.Attributes(), childNodes);
-                }
-            }
-        }
-
-        public WmlDocument(WmlDocument other, params XElement[] replacementParts)
-            : base(other)
-        {
-            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(this))
-            {
-                using (Package package = streamDoc.GetPackage())
-                {
-                    foreach (var replacementPart in replacementParts)
-                    {
-                        XAttribute uriAttribute = replacementPart.Attribute(PtOpenXml.Uri);
-                        if (uriAttribute == null)
-                            throw new OpenXmlPowerToolsException("Replacement part does not contain a Uri as an attribute");
-                        String uri = uriAttribute.Value;
-                        var part = package.GetParts().FirstOrDefault(p => p.Uri.ToString() == uri);
-                        using (Stream partStream = part.GetStream(FileMode.Create, FileAccess.Write))
-                        using (XmlWriter partXmlWriter = XmlWriter.Create(partStream))
-                            replacementPart.Save(partXmlWriter);
-                    }
-                }
-                this.DocumentByteArray = streamDoc.GetModifiedDocument().DocumentByteArray;
-            }
-        }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 3428
TEAMModelOS.SDK/Module/OpenXmlTool/WmlToHtmlConverter.cs


文件差異過大導致無法顯示
+ 0 - 2098
TEAMModelOS.SDK/Module/OpenXmlTool/WmlToXml.cs


文件差異過大導致無法顯示
+ 0 - 2185
TEAMModelOS.SDK/Module/OpenXmlTool/WorksheetAccessor.cs


+ 0 - 463
TEAMModelOS.SDK/Module/OpenXmlTool/XlsxTables.cs

@@ -1,463 +0,0 @@
-// 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.Generic;
-using System.Linq;
-using System.Text;
-using System.Xml.Linq;
-using DocumentFormat.OpenXml.Packaging;
-using System.IO;
-
-namespace OpenXmlPowerTools
-{
-    public class Table
-    {
-        public int Id { get; set; }
-        public string TableName { get; set; }
-        public string DisplayName { get; set; }
-        public XElement TableStyleInfo { get; set; }
-        public string Ref { get; set; }
-        public int LeftColumn { get; set; }
-        public int RightColumn { get; set; }
-        public int TopRow { get; set; }
-        public int BottomRow { get; set; }
-        public int? HeaderRowCount { get; set; }
-        public int? TotalsRowCount { get; set; }
-        public string TableType { get; set; }  // external data query, data in worksheet, or XML data
-        public TableDefinitionPart TableDefinitionPart { get; set; }
-        public WorksheetPart Parent { get; set; }
-        public Table(WorksheetPart parent) { Parent = parent; }
-        public IEnumerable<TableColumn> TableColumns()
-        {
-            XNamespace x = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
-            return TableDefinitionPart
-                .GetXDocument()
-                .Root
-                .Element(x + "tableColumns")
-                .Elements(x + "tableColumn")
-                .Select((c, i) =>
-                    new TableColumn(this)
-                    {
-                        Id = (int)c.Attribute("id"),
-                        ColumnNumber = this.LeftColumn + i,
-                        Name = (string)c.Attribute("name"),
-                        DataDxfId = (int?)c.Attribute("dataDxfId"),
-                        QueryTableFieldId = (int?)c.Attribute("queryTableFieldId"),
-                        UniqueName = (string)c.Attribute("uniqueName"),
-                        ColumnIndex = i,
-                    }
-                );
-        }
-        public IEnumerable<TableRow> TableRows()
-        {
-            string refStart = Ref.Split(':').First();
-            int rowStart = Int32.Parse(XlsxTables.SplitAddress(refStart)[1]);
-            string refEnd = Ref.Split(':').ElementAt(1);
-            int rowEnd = Int32.Parse(XlsxTables.SplitAddress(refEnd)[1]);
-            int headerRowsCount = HeaderRowCount == null ? 0 : (int)HeaderRowCount;
-            int totalRowsCount = TotalsRowCount == null ? 0 : (int)TotalsRowCount;
-            return Parent
-                .Rows()
-                .Skip(headerRowsCount)
-                .SkipLast(totalRowsCount)
-                .Where(r =>
-                {
-                    int rowId = Int32.Parse(r.RowId);
-                    return rowId >= rowStart && rowId <= rowEnd;
-                }
-                )
-                .Select(r => new TableRow(this) { Row = r });
-        }
-    }
-
-    public class TableColumn
-    {
-        public int Id { get; set; }
-        public string Name { get; set; }
-        public int? DataDxfId { get; set; }
-        public int? QueryTableFieldId { get; set; }
-        public string UniqueName { get; set; }
-        public int ColumnNumber { get; set; }
-        public int ColumnIndex { get; set; }
-        public Table Parent { get; set; }
-        public TableColumn(Table parent) { Parent = parent; }
-    }
-
-    public class TableRow
-    {
-        public Row Row { get; set; }
-        public Table Parent { get; set; }
-        public TableRow(Table parent) { Parent = parent; }
-        public TableCell this[string columnName]
-        {
-            get
-            {
-                TableColumn tc = Parent
-                    .TableColumns()
-                    .Where(x => x.Name.ToLower() == columnName.ToLower())
-                    .FirstOrDefault();
-                if (tc == null)
-                    throw new Exception("Invalid column name: " + columnName);
-                string[] refs = Parent.Ref.Split(':');
-                string[] startRefs = XlsxTables.SplitAddress(refs[0]);
-                string columnAddress = XlsxTables.IndexToColumnAddress(XlsxTables.ColumnAddressToIndex(startRefs[0]) + tc.ColumnIndex);
-                Cell cell = Row.Cells().Where(c => c.ColumnAddress == columnAddress).FirstOrDefault();
-                if (cell != null)
-                {
-                    if (cell.Type == "s")
-                        return new TableCell(cell.SharedString);
-                    else
-                        return new TableCell(cell.Value);
-                }
-                else
-                    return new TableCell("");
-            }
-        }
-    }
-
-    public class TableCell : IEquatable<TableCell>
-    {
-        public string Value { get; set; }
-        public TableCell(string v)
-        {
-            Value = v;
-        }
-        public override string ToString()
-        {
-            return Value;
-        }
-        public override bool Equals(object obj)
-        {
-            return this.Value == ((TableCell)obj).Value;
-        }
-        bool IEquatable<TableCell>.Equals(TableCell other)
-        {
-            return this.Value == other.Value;
-        }
-        public override int GetHashCode()
-        {
-            return this.Value.GetHashCode();
-        }
-        public static bool operator ==(TableCell left, TableCell right)
-        {
-            if ((object)left != (object)right) return false;
-            return left.Value == right.Value;
-        }
-        public static bool operator !=(TableCell left, TableCell right)
-        {
-            if ((object)left != (object)right) return false;
-            return left.Value != right.Value;
-        }
-        public static explicit operator string(TableCell cell)
-        {
-            if (cell == null) return null;
-            return cell.Value;
-        }
-        public static explicit operator bool(TableCell cell)
-        {
-            if (cell == null) throw new ArgumentNullException("TableCell");
-            return cell.Value == "1";
-        }
-        public static explicit operator bool?(TableCell cell)
-        {
-            if (cell == null) return null;
-            return cell.Value == "1";
-        }
-        public static explicit operator int(TableCell cell)
-        {
-            if (cell == null) throw new ArgumentNullException("TableCell");
-            return Int32.Parse(cell.Value);
-        }
-        public static explicit operator int?(TableCell cell)
-        {
-            if (cell == null) return null;
-            return Int32.Parse(cell.Value);
-        }
-        public static explicit operator uint(TableCell cell)
-        {
-            if (cell == null) throw new ArgumentNullException("TableCell");
-            return UInt32.Parse(cell.Value);
-        }
-        public static explicit operator uint?(TableCell cell)
-        {
-            if (cell == null) return null;
-            return UInt32.Parse(cell.Value);
-        }
-        public static explicit operator long(TableCell cell)
-        {
-            if (cell == null) throw new ArgumentNullException("TableCell");
-            return Int64.Parse(cell.Value);
-        }
-        public static explicit operator long?(TableCell cell)
-        {
-            if (cell == null) return null;
-            return Int64.Parse(cell.Value);
-        }
-        public static explicit operator ulong(TableCell cell)
-        {
-            if (cell == null) throw new ArgumentNullException("TableCell");
-            return UInt64.Parse(cell.Value);
-        }
-        public static explicit operator ulong?(TableCell cell)
-        {
-            if (cell == null) return null;
-            return UInt64.Parse(cell.Value);
-        }
-        public static explicit operator float(TableCell cell)
-        {
-            if (cell == null) throw new ArgumentNullException("TableCell");
-            return Single.Parse(cell.Value);
-        }
-        public static explicit operator float?(TableCell cell)
-        {
-            if (cell == null) return null;
-            return Single.Parse(cell.Value);
-        }
-        public static explicit operator double(TableCell cell)
-        {
-            if (cell == null) throw new ArgumentNullException("TableCell");
-            return Double.Parse(cell.Value);
-        }
-        public static explicit operator double?(TableCell cell)
-        {
-            if (cell == null) return null;
-            return Double.Parse(cell.Value);
-        }
-        public static explicit operator decimal(TableCell cell)
-        {
-            if (cell == null) throw new ArgumentNullException("TableCell");
-            return Decimal.Parse(cell.Value);
-        }
-        public static explicit operator decimal?(TableCell cell)
-        {
-            if (cell == null) return null;
-            return Decimal.Parse(cell.Value);
-        }
-        public static implicit operator DateTime(TableCell cell)
-        {
-            if (cell == null) throw new ArgumentNullException("TableCell");
-            return new DateTime(1900, 1, 1).AddDays(Int32.Parse(cell.Value) - 2);
-        }
-        public static implicit operator DateTime?(TableCell cell)
-        {
-            if (cell == null) return null;
-            return new DateTime(1900, 1, 1).AddDays(Int32.Parse(cell.Value) - 2);
-        }
-    }
-
-    public class Row
-    {
-        public XElement RowElement { get; set; }
-        public string RowId { get; set; }
-        public string Spans { get; set; }
-        public List<Cell> Cells()
-        {
-            XNamespace s = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
-            SpreadsheetDocument doc = (SpreadsheetDocument)Parent.OpenXmlPackage;
-            SharedStringTablePart sharedStringTable = doc.WorkbookPart.SharedStringTablePart;
-            IEnumerable<XElement> cells = this.RowElement.Elements(S.c);
-            var r = cells
-                .Select(cell => {
-                    var cellType = (string)cell.Attribute("t");
-                    var sharedString = cellType == "s" ?
-                        sharedStringTable
-                        .GetXDocument()
-                        .Root
-                        .Elements(s + "si")
-                        .Skip((int)cell.Element(s + "v"))
-                        .First()
-                        .Descendants(s + "t")
-                        .StringConcatenate(e => (string)e)
-                        : null;
-                    var column = (string)cell.Attribute("r");
-                    var columnAddress = column.Split('0', '1', '2', '3', '4', '5', '6', '7', '8', '9').First();
-                    var columnIndex = XlsxTables.ColumnAddressToIndex(columnAddress);
-                    var newCell = new Cell(this)
-                    {
-                        CellElement = cell,
-                        Row = (string)RowElement.Attribute("r"),
-                        Column = column,
-                        ColumnAddress = columnAddress,
-                        ColumnIndex = columnIndex,
-                        Type = cellType,
-                        Formula = (string)cell.Element(S.f),
-                        Style = (int?)cell.Attribute("s"),
-                        Value = (string)cell.Element(S.v),
-                        SharedString = sharedString
-                    };
-                    return newCell;
-                });
-            var ra = r.ToList();
-            return ra;
-        }
-        public WorksheetPart Parent { get; set; }
-        public Row(WorksheetPart parent) { Parent = parent; }
-    }
-
-    public class Cell
-    {
-        public XElement CellElement { get; set; }
-        public string Row { get; set; }
-        public string Column { get; set; }
-        public string ColumnAddress { get; set; }
-        public int ColumnIndex { get; set; }
-        public string Type { get; set; }
-        public string Value { get; set; }
-        public string Formula { get; set; }
-        public int? Style { get; set; }
-        public string SharedString { get; set; }
-        public Row Parent { get; set; }
-        public Cell(Row parent) { Parent = parent; }
-    }
-
-    public static class XlsxTables
-    {
-        public static IEnumerable<Table> Tables(this SpreadsheetDocument spreadsheet)
-        {
-            foreach (var worksheetPart in spreadsheet.WorkbookPart.WorksheetParts)
-                foreach (var table in worksheetPart.TableDefinitionParts)
-                {
-                    XDocument tableDefDoc = table.GetXDocument();
-
-                    Table t = new Table(worksheetPart)
-                    {
-                        Id = (int)tableDefDoc.Root.Attribute("id"),
-                        TableName = (string)tableDefDoc.Root.Attribute("name"),
-                        DisplayName = (string)tableDefDoc.Root.Attribute("displayName"),
-                        TableStyleInfo = tableDefDoc.Root.Element(S.tableStyleInfo),
-                        Ref = (string)tableDefDoc.Root.Attribute("ref"),
-                        TotalsRowCount = (int?)tableDefDoc.Root.Attribute("totalsRowCount"),
-                        //HeaderRowCount = (int?)tableDefDoc.Root.Attribute("headerRowCount"),
-                        HeaderRowCount = 1,  // currently there always is a header row
-                        TableType = (string)tableDefDoc.Root.Attribute("tableType"),
-                        TableDefinitionPart = table
-                    };
-                    int leftColumn, topRow, rightColumn, bottomRow;
-                    ParseRange(t.Ref, out leftColumn, out topRow, out rightColumn, out bottomRow);
-                    t.LeftColumn = leftColumn;
-                    t.TopRow = topRow;
-                    t.RightColumn = rightColumn;
-                    t.BottomRow = bottomRow;
-                    yield return t;
-                }
-        }
-
-        public static void ParseRange(string theRef, out int leftColumn, out int topRow, out int rightColumn, out int bottomRow)
-        {
-            // C5:E7
-            var spl = theRef.Split(':');
-            string refStart = spl.First();
-            var refStartSplit = XlsxTables.SplitAddress(refStart);
-            leftColumn = XlsxTables.ColumnAddressToIndex(refStartSplit[0]);
-            topRow = Int32.Parse(refStartSplit[1]);
-
-            string refEnd = spl.ElementAt(1);
-            var refEndSplit = XlsxTables.SplitAddress(refEnd);
-            rightColumn = XlsxTables.ColumnAddressToIndex(refEndSplit[0]);
-            bottomRow = Int32.Parse(refEndSplit[1]);
-        }
-
-        public static Table Table(this SpreadsheetDocument spreadsheet,
-            string tableName)
-        {
-            return spreadsheet.Tables().Where(t => t.TableName.ToLower() == tableName.ToLower()).FirstOrDefault();
-        }
-
-        public static IEnumerable<Row> Rows(this WorksheetPart worksheetPart)
-        {
-            XNamespace s = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
-            var rows = worksheetPart
-                .GetXDocument()
-                .Root
-                .Elements(S.sheetData)
-                .Elements(S.row)
-                .Select(r =>
-                {
-                    var row = new Row(worksheetPart)
-                    {
-                        RowElement = r,
-                        RowId = (string)r.Attribute("r"),
-                        Spans = (string)r.Attribute("spans")
-                    };
-                    return row;
-                });
-            return rows;
-        }
-
-        public static string[] SplitAddress(string address)
-        {
-            int i;
-            for (i = 0; i < address.Length; i++)
-                if (address[i] >= '0' && address[i] <= '9')
-                    break;
-            if (i == address.Length)
-                throw new FileFormatException("Invalid spreadsheet.  Bad cell address.");
-            return new[] {
-                address.Substring(0, i),
-                address.Substring(i)
-            };
-        }
-
-        public static string IndexToColumnAddress(int index)
-        {
-            if (index < 26)
-            {
-                char c = (char)((int)'A' + index);
-                string s = new string(c, 1);
-                return s;
-            }
-            if (index < 702)
-            {
-                int i = index - 26;
-                int i1 = (int)(i / 26);
-                int i2 = i % 26;
-                string s = new string((char)((int)'A' + i1), 1) +
-                    new string((char)((int)'A' + i2), 1);
-                return s;
-            }
-            if (index < 18278)
-            {
-                int i = index - 702;
-                int i1 = (int)(i / 676);
-                i = i - i1 * 676;
-                int i2 = (int)(i / 26);
-                int i3 = i % 26;
-                string s = new string((char)((int)'A' + i1), 1) +
-                    new string((char)((int)'A' + i2), 1) +
-                    new string((char)((int)'A' + i3), 1);
-                return s;
-            }
-            throw new Exception("Invalid column address");
-        }
-
-        public static int ColumnAddressToIndex(string columnAddress)
-        {
-            if (columnAddress.Length == 1)
-            {
-                char c = columnAddress[0];
-                int i = c - 'A';
-                return i;
-            }
-            if (columnAddress.Length == 2)
-            {
-                char c1 = columnAddress[0];
-                char c2 = columnAddress[1];
-                int i1 = c1 - 'A';
-                int i2 = c2 - 'A';
-                return (i1 + 1) * 26 + i2;
-            }
-            if (columnAddress.Length == 3)
-            {
-                char c1 = columnAddress[0];
-                char c2 = columnAddress[1];
-                char c3 = columnAddress[2];
-                int i1 = c1 - 'A';
-                int i2 = c2 - 'A';
-                int i3 = c3 - 'A';
-                return (i1 + 1) * 676 + (i2 + 1) * 26 + i3;
-            }
-            throw new FileFormatException("Invalid spreadsheet: Invalid column address.");
-        }
-    }
-}

+ 20 - 54
TEAMModelOS/Controllers/Exam/ImportExerciseController.cs

@@ -27,8 +27,8 @@ using TEAMModelOS.SDK.Extension;
 using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
 using TEAMModelOS.SDK.Module.AzureBlob.Container;
 using TEAMModelOS.Services;
-using TEAMModelOS.Servicess.Exam;
-using TEAMModelOS.Servicess.PowerPoint.Implement;
+using HTEXLib.Translator;
+using HTEXLib.DOCX.Models;
 
 namespace TEAMModelOS.Controllers
 {
@@ -36,16 +36,22 @@ namespace TEAMModelOS.Controllers
     [ApiController]
     public class ImportExerciseController : BaseController
     {
-        public HtexGenerator htexGenerator { get; set; }
+        public PPTX2HTEXTranslator _PPTX2HTEXTranslator { get; set; }
+        public DOXC2HTMLTranslator _DOXC2HTMLTranslator { get; set; }
+        public HTML2ITEMTranslator _HTML2ITEMTranslator { get; set; }
         //  private readonly IHtexService htexService;
         private readonly AzureStorageFactory _azureStorage;
         private readonly IWebHostEnvironment _webHostEnvironment;
         private  List<LangConfig> langConfigs { get; set; }
         private readonly IHttpClientFactory _clientFactory;
-        public ImportExerciseController(   AzureStorageFactory azureStorage, IWebHostEnvironment webHostEnvironment, HtexGenerator htexGenerator, IHttpClientFactory clientFactory)
+        public ImportExerciseController(   AzureStorageFactory azureStorage, IWebHostEnvironment webHostEnvironment,
+            PPTX2HTEXTranslator PPTX2HTEXTranslator, IHttpClientFactory clientFactory,
+            DOXC2HTMLTranslator DOXC2HTMLTranslator, HTML2ITEMTranslator HTML2ITEMTranslator)
         {
+            _HTML2ITEMTranslator = HTML2ITEMTranslator;
+            _DOXC2HTMLTranslator = DOXC2HTMLTranslator;
             _clientFactory = clientFactory;
-            this.htexGenerator = htexGenerator;
+            this._PPTX2HTEXTranslator = PPTX2HTEXTranslator;
             _webHostEnvironment = webHostEnvironment;
             _azureStorage = azureStorage;
             string path = _webHostEnvironment.ContentRootPath + "/JsonFile/Core/LangConfig.json";
@@ -62,20 +68,7 @@ namespace TEAMModelOS.Controllers
             string text = builder.ToString();
             langConfigs = text.ToObject<List<LangConfig>>();
         }
-        /// <summary>
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [HttpPost("load-doc")]
-        [RequestSizeLimit(102_400_000_00)] //最大10000m左右
-        public async Task<BaseResponse> LoadDoc([FromForm] IFormFile file)
-        {
-            ResponseBuilder responseBuilder = new ResponseBuilder();
-
-            Dictionary<string, object> model = await HtexService.LoadDoc(_azureStorage, file);
-            return responseBuilder.Data(model).build();
-        }
-
+       
 
         /// <summary>
         /// {"url":"https://***.blob.core.cn/xxx/1.pptx"}
@@ -179,15 +172,17 @@ namespace TEAMModelOS.Controllers
         /// <returns></returns>
         [HttpPost("upload-word")]
         [RequestSizeLimit(102_400_000_00)] //最大10000m左右
-        public async Task<IActionResult> UploadWord([FromForm] IFormFile file)
+        public   IActionResult UploadWord([FromForm] IFormFile file)
         {
           //  ResponseBuilder responseBuilder = new ResponseBuilder();
             if (!FileType.GetExtention(file.FileName).ToLower().Equals("docx"))
             {
                 return BadRequest(new Dictionary<string, object> { {"msg", "type is not docx!" },{ "code",ResponseCode.FAILED} });
             }
-            Dictionary<string, object> model = await ImportExerciseService.UploadWord(_azureStorage, file);
-            return Ok(model);
+
+            var doc= _DOXC2HTMLTranslator.Translate(file.OpenReadStream());
+           // Dictionary<string, object> model = await ImportExerciseService.UploadWord(_azureStorage, file);
+            return Ok(doc);
         }
 
         /// <summary>
@@ -210,8 +205,7 @@ namespace TEAMModelOS.Controllers
             if (flag && htmlString != null && !string.IsNullOrEmpty(htmlString.ToString()))
             {
                 LangConfig langConfig= langConfigs.Where(x => x.Lang == lang.ToString()).FirstOrDefault();
-                HtmlAnalyzeService htmlAnalyzeService = new HtmlAnalyzeService(langConfig);
-                List<ItemInfo> exercises = htmlAnalyzeService.AnalyzeWordAsync(htmlString.ToString());
+                var exercises= _HTML2ITEMTranslator.Translate(htmlString.ToString(), langConfig);
                 return Ok(exercises);
             }
             else
@@ -219,41 +213,13 @@ namespace TEAMModelOS.Controllers
                 return BadRequest();
             }
         }
-        /// <summary>
-        /// htmlString 
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [HttpPost("HtmlToHtex")]
-        public async Task<IActionResult> HtmlToHtex(JsonElement request)
-        {
-            ResponseBuilder builder = ResponseBuilder.custom();
-/*            Dictionary<string, object> dict = new Dictionary<string, object>();
-            var emobj = request.EnumerateObject();
-            while (emobj.MoveNext())
-            {
-                dict[emobj.Current.Name] = emobj.Current.Value;
-            }*/
-            bool flag = request.TryGetProperty("htmlString", out JsonElement htmlString);
-            bool flagLang = request.TryGetProperty("lang", out JsonElement lang);
-            if (flag && htmlString.ToString() != null && !string.IsNullOrEmpty(htmlString.ToString()))
-            {
-                LangConfig langConfig = langConfigs.Where(x => x.Lang == lang.ToString()).FirstOrDefault();
-                HtmlAnalyzeService htmlAnalyzeService = new HtmlAnalyzeService(langConfig);
-                Models.PowerPoint.Htex exercises = await HtexService.AnalyzeHtmlToHtex(_azureStorage, htmlString.ToString(), lang.ToString(), htmlAnalyzeService);
-                return Ok(exercises);
-            }
-            else
-            {
-                return BadRequest("语言设置错误");
-            }
-        }
+       
 
         private async Task<string> PPTXTranslator(string id, string FileName, Stream streamFile)
         {
             var status = await _azureStorage.GetBlobServiceClient().DelectBlobs(id, $"res/{FileName}");
             string shaCode = Guid.NewGuid().ToString("N");
-            HTEXLib.Htex htex = htexGenerator.Generator(streamFile);
+            HTEXLib.Htex htex = _PPTX2HTEXTranslator.Translate(streamFile);
             htex.name = FileName;
             var slides = htex.slides;
             List<Task> tasks = new List<Task>();

+ 0 - 24
TEAMModelOS/Models/Dto/LangConfig.cs

@@ -1,24 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace TEAMModelOS.Models.Dto
-{
-    public class LangConfig
-    {
-        public string Lang { get; set; }
-        public string Name { get; set; }
-        public string Alias { get; set; }
-        public ItemConfig Item { get; set; }
-    }
-    public class ItemConfig { 
-        public Dictionary<string, string> Type { get; set; }
-        public string AnswerTag { get; set; }
-        public string AnalysisTag { get; set; }
-        public string EndedTag { get; set; }
-        public string Options { get; set; }
-        public string Start { get; set; }
-        public string End { get; set; }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 551
TEAMModelOS/Services/Evaluation/HtmlAnalyzeService.cs


+ 0 - 187
TEAMModelOS/Services/Evaluation/ImportExerciseService.cs

@@ -1,187 +0,0 @@
-using DocumentFormat.OpenXml.Packaging;
-using HtmlAgilityPack;
-using Microsoft.AspNetCore.Http;
-using OpenXmlPowerTools;
-using System;
-using System.Collections.Generic;
-using System.Drawing.Imaging;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Threading.Tasks;
-using System.Xml.Linq;
-using TEAMModelOS.SDK.Context.Constant;
-using TEAMModelOS.SDK.DI;
-using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
-using TEAMModelOS.SDK.Helper.Common.FileHelper;
-using TEAMModelOS.SDK.Helper.Common.StringHelper;
-using TEAMModelOS.SDK.Helper.Security.ShaHash;
-using TEAMModelOS.SDK.Module.AzureBlob.Container;
-
-
-namespace TEAMModelOS.Servicess.Exam
-{
-    public static class ImportExerciseService 
-    {
-      
-       
-     //   private readonly IAzureBlobDBRepository azureBlobDBRepository;
-       // private readonly AzureStorageFactory azureTableDBRepository;
-        //public ImportExerciseService(IAzureBlobDBRepository _azureBlobDBRepository, AzureStorageFactory _azureTableDBRepository)
-        //{
-        //   // azureBlobDBRepository = _azureBlobDBRepository;
-        //    azureTableDBRepository = _azureTableDBRepository;
-        //}
-        public static async Task<Dictionary<string, object>> UploadWord(this AzureStorageFactory azureStorage, IFormFile file)
-        {
-
-            Dictionary<string, object> resdict = new Dictionary<string, object>();
-            string shaCode = ShaHashHelper.GetSHA1(file.OpenReadStream());
-            long length = file.Length;
-            Dictionary<string, object> dict = new Dictionary<string, object> { { "Sha1Code", shaCode } };
-            List<AzureBlobModel> models = await azureStorage.FindListByDict<AzureBlobModel>(dict);
-
-            //if (models.IsNotEmpty())
-            //{
-            //    resdict.Add("HtmlString", HttpHelper.HttpGet(models[0].BlobUrl));
-            //    resdict.Add("Sha1Code", models[0].Sha1Code);
-            //    return resdict;
-            //}
-           string folder = shaCode + "";
-            //System.IO.Directory.CreateDirectory(folder);
-            // var filePath = folder + "\\" + file.FileName;
-            //using (var stream = new FileStream(filePath, FileMode.Create))
-            //{
-            //    await file.CopyToAsync(stream);
-            //}
-            var htmlInfo = ConvertDocxToHtml(file, folder);
-            AzureBlobModel model = await AzureStorageBlobExtensions.UploadFileByContainer(azureStorage, "teammodelos", htmlInfo.htmlString, "exercise", htmlInfo.blobPath, false);
-            model.Sha1Code = shaCode;
-            await azureStorage.Save<AzureBlobModel>(model);
-           // FileHelper.DeleteDirAndFiles(BaseConfigModel.ContentRootPath + "/Upload");
-            resdict.Add("HtmlString", htmlInfo.htmlString);
-            resdict.Add("Sha1Code", shaCode);
-            return resdict;
-        }
-        public static dynamic ConvertDocxToHtml(IFormFile file, string folder)
-        {
-            string FolderName =  DateTime.Now.ToString("yyyyMMdd")+"/"+ folder;
-            byte[] byteArray = new byte[file.OpenReadStream().Length];
-            file.OpenReadStream().Read(byteArray, 0, byteArray.Length);
-            //byte[] bytes = new byte[stream.Length];
-            using (MemoryStream memoryStream = new MemoryStream())
-            {
-                memoryStream.Write(byteArray, 0, byteArray.Length);
-                using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true))
-                {
-                    int imageCounter = 0;
-                    WmlToHtmlConverterSettings settings = new WmlToHtmlConverterSettings()
-                    {
-                        PageTitle = "",
-                        AdditionalCss = "body { margin: 1cm auto; max-width: 20cm; padding: 0; }",
-
-                        FabricateCssClasses = true,
-                        CssClassPrefix = "pt-",
-                        RestrictToSupportedLanguages = false,
-                        RestrictToSupportedNumberingFormats = false,
-                        ImageHandler = imageInfo =>
-                        {
-                            ++imageCounter;
-                            string extension = imageInfo.ContentType.Split('/')[1].ToLower();
-                            ImageFormat imageFormat = null;
-                            if (extension.Equals("png")) imageFormat = ImageFormat.Png;
-                            else if (extension.Equals("gif")) imageFormat = ImageFormat.Gif;
-                            else if (extension.Equals("bmp")) imageFormat = ImageFormat.Bmp;
-                            else if (extension.Equals("jpeg")) imageFormat = ImageFormat.Jpeg;
-                            else if (extension.Equals("tiff"))
-                            {
-                                extension = "gif";
-                                imageFormat = ImageFormat.Gif;
-                            }
-                            else if (extension.Equals("x-wmf"))
-                            {
-                                extension = "wmf";
-                                imageFormat = ImageFormat.Wmf;
-                            }
-
-                            if (imageFormat == null) return null;
-                            string base64 = null;
-                            string mimeType = null;
-                            string shaCode = null;
-                            try
-                            {
-                                if (extension.Equals("wmf"))
-                                {
-                                    var buffer = Encoding.Default.GetBytes(imageInfo.Mathxml);
-                                    base64 = System.Convert.ToBase64String(buffer);
-                                    mimeType = "image/svg+xml";
-                                    shaCode = ShaHashHelper.GetSHA1(new MemoryStream(buffer));
-                                }
-                                else
-                                {
-                                    ImageFormat format = imageInfo.Bitmap.RawFormat;
-                                    ImageCodecInfo codec = ImageCodecInfo.GetImageDecoders()
-                                                                .First(c => c.FormatID == format.Guid);
-                                    mimeType = codec.MimeType;
-                                    using (MemoryStream ms = new MemoryStream())
-                                    {
-
-                                        imageInfo.Bitmap.Save(ms, imageFormat);
-                                        var ba = ms.ToArray();
-                                        base64 = System.Convert.ToBase64String(ba);
-                                        shaCode = ShaHashHelper.GetSHA1(ms);
-                                    }
-                                }
-                            }
-                            catch (System.Runtime.InteropServices.ExternalException)
-                            { return null; }
-
-                            string imageSource =
-                                    string.Format("data:{0};base64,{1}", mimeType, base64);
-                            #region 处理图片存到Bolb
-                            string[] strs = imageSource.Split(',');
-                            string fileExt = StringHelper.SubMidString(strs[0], ":", ";");
-                            if (ContentTypeDict.extdict.TryGetValue(fileExt, out string ext))
-                            {
-                                fileExt = ext;
-                            }
-                            else
-                            {
-                                //解决多种扩展名不能获取的
-                                string[] sp = StringHelper.SubMidString(strs[0], "/", ";").Split("-");
-                                fileExt = sp[sp.Length - 1];
-                                sp = fileExt.Split("+");
-                                fileExt = "." + sp[sp.Length - 1];
-                            }
-                            string url = "data:" + mimeType + ";base64," + strs[1];
-                            url = url.Replace("\r\n", "");
-                            
-                            //Stream stream = new MemoryStream(Convert.FromBase64String(strs[1]));
-                            string filename = shaCode + fileExt;
-                          //  AzureBlobModel model = azureBlobDBRepository.UploadFileByFolderNAsyn(stream, FolderName, filename, "exercise", false);
-                            #endregion
-                            XElement img = new XElement(Xhtml.img,
-                                 new XAttribute(NoNamespace.src, url),
-                                  //  new XAttribute(NoNamespace.src, model.BlobUrl),
-                                    imageInfo.ImgStyleAttribute,
-                                    imageInfo.AltText != null ?
-                                        new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
-                            //stream.Close();
-                            return img;
-                        }
-                    };
-                    // XElement html = HtmlConverter.ConvertToHtml(doc, settings);
-                    // File.WriteAllText(@"E:\document\kk.html", html.ToStringNewLineOnAttributes());
-                    XElement htmlElement = WmlToHtmlConverter.ConvertToHtml(doc, settings);
-                    var htmls = new XDocument(new XDocumentType("html", null, null, null), htmlElement);
-                    var htmlString = htmls.ToString(SaveOptions.DisableFormatting);
-                    //引入MathJax插件
-                    htmlString = htmlString + "<script type=\"text/javascript\" src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"></script>";
-                    //File.WriteAllText(folder + "/" + "index.html", htmlString);
-                    return new { htmlString, blobPath = FolderName + "/" + "index.html" };
-                };
-            }
-        }
-    }
-}

文件差異過大導致無法顯示
+ 0 - 3177
TEAMModelOS/Services/PowerPoint/HtexService.cs


文件差異過大導致無法顯示
+ 0 - 1072
TEAMModelOS/Services/PowerPoint/ShapeHelper.cs


文件差異過大導致無法顯示
+ 0 - 11120
TEAMModelOS/Services/PowerPoint/ShapeSvg.cs


+ 2 - 1
TEAMModelOS/Startup.cs

@@ -8,6 +8,7 @@ using System.Text.Json;
 using System.Threading;
 using System.Threading.Tasks;
 using HTEXLib.Builders;
+using HTEXLib.Translator;
 using Microsoft.AspNetCore.Authentication.JwtBearer;
 using Microsoft.AspNetCore.Builder;
 using Microsoft.AspNetCore.Hosting;
@@ -109,7 +110,7 @@ namespace TEAMModelOS
             CSRedis.CSRedisClient.Serialize = obj => System.Text.Json.JsonSerializer.Serialize(obj);
             CSRedis.CSRedisClient.Deserialize = (json, type) => System.Text.Json.JsonSerializer.Deserialize(json, type);
             RedisHelper.Initialization(csredis);
-            services.AddHtexGenerator();
+            services.AddHtexTranslator();
         }
 
         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

+ 2 - 1
TEAMModelOS/TEAMModelOS.csproj

@@ -6,7 +6,7 @@
   <ItemGroup>
     <PackageReference Include="Caching.CSRedis" Version="3.6.50" />
     <PackageReference Include="CSRedisCore" Version="3.6.5" />
-    <PackageReference Include="HTEXLib" Version="1.1.1" />
+    <PackageReference Include="HTEXLib" Version="2.0.2" />
     <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.6" />
       <PackageReference Include="VueCliMiddleware" Version="3.1.2" />  </ItemGroup>
   <PropertyGroup>
@@ -45,6 +45,7 @@
   <ItemGroup>
     <Folder Include="Controllers\Common\" />
     <Folder Include="JwtRsaFile\" />
+    <Folder Include="Services\Evaluation\" />
     <Folder Include="wwwroot\" />
   </ItemGroup>