xceed.com 8 years ago
parent
commit
2bead9e2c0
100 changed files with 758 additions and 31445 deletions
  1. 0
    239
      .gitignore
  2. 0
    8
      .travis.yml
  3. 0
    543
      BuildProcessTemplates/DefaultTemplate.11.1.xaml
  4. 0
    602
      BuildProcessTemplates/DefaultTemplate.xaml
  5. 0
    208
      BuildProcessTemplates/LabDefaultTemplate.11.xaml
  6. 0
    76
      BuildProcessTemplates/UpgradeTemplate.xaml
  7. 0
    33
      DocX.Xamarin.sln
  8. 0
    4459
      DocX.cs
  9. 0
    107
      DocX.iOS.Test/DocX.iOS.Test.csproj
  10. 0
    6
      DocX.iOS.Test/Entitlements.plist
  11. 0
    43
      DocX.iOS.Test/Info.plist
  12. 0
    162
      DocX.iOS.Test/Resources/Images.xcassets/AppIcons.appiconset/Contents.json
  13. 0
    32
      DocX.iOS.Test/Resources/LaunchScreen.xib
  14. 0
    143
      DocX.iOS.Test/Sources/App.cs
  15. 0
    200
      DocX.iOS/DocX.iOS.csproj
  16. 0
    27
      DocX.iOS/Properties/AssemblyInfo.cs
  17. 0
    89
      DocX.iOS/System/Drawing/ColorTranslator.cs
  18. 0
    20
      DocX.iOS/System/Drawing/FontFamily.cs
  19. 0
    85
      DocX.iOS/System/Drawing/Image.cs
  20. 0
    163
      DocX.iOS/System/IO/Packaging/Check.cs
  21. 0
    17
      DocX.iOS/System/IO/Packaging/CompressionOption.cs
  22. 0
    185
      DocX.iOS/System/IO/Packaging/PackUriHelper.cs
  23. 0
    109
      DocX.iOS/System/IO/Packaging/PackUriParser.cs
  24. 0
    488
      DocX.iOS/System/IO/Packaging/Package.cs
  25. 0
    257
      DocX.iOS/System/IO/Packaging/PackagePart.cs
  26. 0
    29
      DocX.iOS/System/IO/Packaging/PackagePartCollection.cs
  27. 0
    91
      DocX.iOS/System/IO/Packaging/PackageProperties.cs
  28. 0
    355
      DocX.iOS/System/IO/Packaging/PackagePropertiesPart.cs
  29. 0
    59
      DocX.iOS/System/IO/Packaging/PackageRelationship.cs
  30. 0
    29
      DocX.iOS/System/IO/Packaging/PackageRelationshipCollection.cs
  31. 0
    14
      DocX.iOS/System/IO/Packaging/TargetMode.cs
  32. 0
    266
      DocX.iOS/System/IO/Packaging/ZipPackage.cs
  33. 0
    77
      DocX.iOS/System/IO/Packaging/ZipPackagePart.cs
  34. 0
    131
      DocX.iOS/System/IO/Packaging/ZipPartStream.cs
  35. 0
    758
      DocX.iOS/Zip/ZipStorer.cs
  36. 0
    53
      DocX.sln
  37. 0
    10
      DocX.vssscc
  38. 0
    13
      DocX/Bookmark.cs
  39. 0
    17
      DocX/BookmarkCollection.cs
  40. 0
    31
      DocX/Border.cs
  41. 0
    118
      DocX/Charts/Axis.cs
  42. 0
    102
      DocX/Charts/BarChart.cs
  43. 0
    477
      DocX/Charts/Chart.cs
  44. 0
    50
      DocX/Charts/LineChart.cs
  45. 0
    22
      DocX/Charts/PieChart.cs
  46. 0
    85
      DocX/Charts/XElementHelpers.cs
  47. 0
    1048
      DocX/Container.cs
  48. 0
    29
      DocX/Content.cs
  49. 0
    17
      DocX/ContentCollection.cs
  50. 0
    107
      DocX/CustomProperty.cs
  51. 0
    24
      DocX/DocProperty.cs
  52. 0
    4598
      DocX/DocX.cs
  53. 0
    10
      DocX/DocX.csproj.vspscc
  54. 0
    8
      DocX/DocumentTypes.cs
  55. 0
    59
      DocX/ExtensionsHeadings.cs
  56. 0
    38
      DocX/Font.cs
  57. 0
    172
      DocX/Footer.cs
  58. 0
    14
      DocX/Footers.cs
  59. 0
    27
      DocX/FormattedText.cs
  60. 0
    548
      DocX/Formatting.cs
  61. 0
    197
      DocX/Header.cs
  62. 0
    13
      DocX/Headers.cs
  63. BIN
      DocX/Help/DocX v1.0.0.10 - Documentation.chm
  64. BIN
      DocX/Help/Read Me.docx
  65. 0
    773
      DocX/HelperFunctions.cs
  66. 0
    232
      DocX/Hyperlink.cs
  67. 0
    9
      DocX/IContentContainer.cs
  68. 0
    9
      DocX/IParagraphContainer.cs
  69. 0
    96
      DocX/Image.cs
  70. BIN
      DocX/KeyWithoutPassword.snk
  71. 0
    7
      DocX/License/License.html
  72. 0
    233
      DocX/List.cs
  73. 0
    87
      DocX/PackagePartStream.cs
  74. 0
    74
      DocX/PageLayout.cs
  75. 0
    4732
      DocX/Paragraph.cs
  76. 0
    421
      DocX/Picture.cs
  77. 0
    44
      DocX/Properties/AssemblyInfo.cs
  78. 0
    17
      DocX/Section.cs
  79. 0
    3910
      DocX/Table.cs
  80. 0
    103
      DocX/TableOfContents.cs
  81. 0
    310
      DocX/_BaseClasses.cs
  82. 0
    97
      DocX/_Extensions.cs
  83. 0
    88
      Documentation/Documentation.shfbproj
  84. 0
    10
      Documentation/Documentation.shfbproj.vspscc
  85. 0
    97
      Examples/Examples.csproj
  86. 0
    10
      Examples/Examples.csproj.vspscc
  87. 111
    1993
      Examples/Program.cs
  88. 15
    23
      Examples/Properties/AssemblyInfo.cs
  89. 0
    73
      Examples/RelativeDirectory.cs
  90. 115
    0
      Examples/Samples/Bookmark/BookmarkSample.cs
  91. BIN
      Examples/Samples/Bookmark/Resources/DocumentWithBookmarks.docx
  92. 61
    0
      Examples/Samples/Chart/ChartData.cs
  93. 207
    0
      Examples/Samples/Chart/ChartSample.cs
  94. 178
    0
      Examples/Samples/Document/DocumentSample.cs
  95. BIN
      Examples/Samples/Document/Resources/First.docx
  96. BIN
      Examples/Samples/Document/Resources/ReplaceText.docx
  97. BIN
      Examples/Samples/Document/Resources/Second.docx
  98. BIN
      Examples/Samples/Document/Resources/Template.docx
  99. 71
    0
      Examples/Samples/Equation/EquationSample.cs
  100. 0
    0
      Examples/Samples/HeaderFooter/HeaderFooterSample.cs

+ 0
- 239
.gitignore View File

@@ -1,239 +0,0 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Microsoft Azure ApplicationInsights config file
ApplicationInsights.config
# Windows Store app package directory
AppPackages/
BundleArtifacts/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
# FAKE - F# Make
.fake/
Documentation/Help/Documentation.chw
DocX/bin/Debug/DocX.dll

+ 0
- 8
.travis.yml View File

@@ -1,8 +0,0 @@
language: csharp
solution: DocX.sln
install:
- nuget restore DocX.sln
- nuget install NUnit.Console -Version 3.4.1 -OutputDirectory testrunner
script:
- xbuild /p:Configuration=Debug DocX.sln
- mono --debug ./testrunner/NUnit.ConsoleRunner.3.4.1/tools/nunit3-console.exe ./UnitTests/bin/Debug/UnitTests.dll

+ 0
- 543
BuildProcessTemplates/DefaultTemplate.11.1.xaml View File

@@ -1,543 +0,0 @@
<Activity mc:Ignorable="sad" x:Class="TfsBuild.Process" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mt="clr-namespace:Microsoft.TeamFoundation;assembly=Microsoft.TeamFoundation.Common" xmlns:mtbc="clr-namespace:Microsoft.TeamFoundation.Build.Client;assembly=Microsoft.TeamFoundation.Build.Client" xmlns:mtbw="clr-namespace:Microsoft.TeamFoundation.Build.Workflow;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtbwa="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Activities;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtbwt="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Tracking;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mttbb="clr-namespace:Microsoft.TeamFoundation.TestImpact.BuildIntegration.BuildActivities;assembly=Microsoft.TeamFoundation.TestImpact.BuildIntegration" xmlns:mtvc="clr-namespace:Microsoft.TeamFoundation.VersionControl.Client;assembly=Microsoft.TeamFoundation.VersionControl.Client" xmlns:mtvco="clr-namespace:Microsoft.TeamFoundation.VersionControl.Common;assembly=Microsoft.TeamFoundation.VersionControl.Common" xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:sad="http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation" xmlns:sad1="clr-namespace:System.Activities.Debugger;assembly=System.Activities" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib" xmlns:sl="clr-namespace:System.Linq;assembly=System.Core" xmlns:this="clr-namespace:TfsBuild;" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<x:Members>
<x:Property Name="BuildSettings" Type="InArgument(mtbwa:BuildSettings)" />
<x:Property Name="TestSpecs" Type="InArgument(mtbwa:TestSpecList)" />
<x:Property Name="BuildNumberFormat" Type="InArgument(x:String)" />
<x:Property Name="SolutionSpecificBuildOutputs" Type="InArgument(x:Boolean)" />
<x:Property Name="CleanWorkspace" Type="InArgument(mtbwa:CleanWorkspaceOption)" />
<x:Property Name="RunCodeAnalysis" Type="InArgument(mtbwa:CodeAnalysisOption)" />
<x:Property Name="SourceAndSymbolServerSettings" Type="InArgument(mtbwa:SourceAndSymbolServerSettings)" />
<x:Property Name="AgentSettings" Type="InArgument(mtbwa:AgentSettings)" />
<x:Property Name="AssociateChangesetsAndWorkItems" Type="InArgument(x:Boolean)" />
<x:Property Name="CreateWorkItem" Type="InArgument(x:Boolean)" />
<x:Property Name="MSBuildArguments" Type="InArgument(x:String)" />
<x:Property Name="MSBuildPlatform" Type="InArgument(mtbwa:ToolPlatform)" />
<x:Property Name="MSBuildMultiProc" Type="InArgument(x:Boolean)" />
<x:Property Name="PerformTestImpactAnalysis" Type="InArgument(x:Boolean)" />
<x:Property Name="CreateLabel" Type="InArgument(x:Boolean)" />
<x:Property Name="DisableTests" Type="InArgument(x:Boolean)" />
<x:Property Name="GetVersion" Type="InArgument(x:String)" />
<x:Property Name="PrivateDropLocation" Type="InArgument(x:String)" />
<x:Property Name="Verbosity" Type="InArgument(mtbw:BuildVerbosity)" />
<x:Property Name="Metadata" Type="mtbw:ProcessParameterMetadataCollection" />
<x:Property Name="SupportedReasons" Type="mtbc:BuildReason" />
<x:Property Name="BuildProcessVersion" Type="x:String" />
</x:Members>
<this:Process.BuildSettings>[New Microsoft.TeamFoundation.Build.Workflow.Activities.BuildSettings()]</this:Process.BuildSettings>
<this:Process.DisableTests>[False]</this:Process.DisableTests>
<this:Process.TestSpecs>[New Microsoft.TeamFoundation.Build.Workflow.Activities.TestSpecList(New Microsoft.TeamFoundation.Build.Workflow.Activities.AgileTestPlatformSpec("**\*test*.dll"))]</this:Process.TestSpecs>
<this:Process.BuildNumberFormat>["$(BuildDefinitionName)_$(Date:yyyyMMdd)$(Rev:.r)"]</this:Process.BuildNumberFormat>
<this:Process.SolutionSpecificBuildOutputs>[False]</this:Process.SolutionSpecificBuildOutputs>
<this:Process.AssociateChangesetsAndWorkItems>[True]</this:Process.AssociateChangesetsAndWorkItems>
<this:Process.CreateWorkItem>[True]</this:Process.CreateWorkItem>
<this:Process.CleanWorkspace>[Microsoft.TeamFoundation.Build.Workflow.Activities.CleanWorkspaceOption.All]</this:Process.CleanWorkspace>
<this:Process.MSBuildArguments>
<InArgument x:TypeArguments="x:String" />
</this:Process.MSBuildArguments>
<this:Process.RunCodeAnalysis>[Microsoft.TeamFoundation.Build.Workflow.Activities.CodeAnalysisOption.AsConfigured]</this:Process.RunCodeAnalysis>
<this:Process.MSBuildMultiProc>[True]</this:Process.MSBuildMultiProc>
<this:Process.MSBuildPlatform>[Microsoft.TeamFoundation.Build.Workflow.Activities.ToolPlatform.Auto]</this:Process.MSBuildPlatform>
<this:Process.PerformTestImpactAnalysis>[True]</this:Process.PerformTestImpactAnalysis>
<this:Process.SourceAndSymbolServerSettings>[New Microsoft.TeamFoundation.Build.Workflow.Activities.SourceAndSymbolServerSettings(True, Nothing)]</this:Process.SourceAndSymbolServerSettings>
<this:Process.CreateLabel>[True]</this:Process.CreateLabel>
<this:Process.GetVersion>
<InArgument x:TypeArguments="x:String" />
</this:Process.GetVersion>
<this:Process.AgentSettings>[New Microsoft.TeamFoundation.Build.Workflow.Activities.AgentSettings() With {.MaxWaitTime = New System.TimeSpan(4, 0, 0), .MaxExecutionTime = New System.TimeSpan(0, 0, 0), .TagComparison = Microsoft.TeamFoundation.Build.Workflow.Activities.TagComparison.MatchExactly }]</this:Process.AgentSettings>
<this:Process.Verbosity>[Microsoft.TeamFoundation.Build.Workflow.BuildVerbosity.Normal]</this:Process.Verbosity>
<this:Process.Metadata>
<mtbw:ProcessParameterMetadataCollection>
<mtbw:ProcessParameterMetadata BrowsableWhen="EditingDefinition" Category="#300 Advanced" DisplayName="MSBuild Multi-Proc" Description="Enable MSBuid Multi-proc to build your solutions' projects in parallel, when possible, using all available processors on the build server." ParameterName="MSBuildMultiProc" />
<mtbw:ProcessParameterMetadata BrowsableWhen="EditingDefinition" Category="#300 Advanced" DisplayName="Solution Specific Build Outputs" Description="True will put build outputs into folders based on the solution name. False will put all build outputs into the same folder." ParameterName="SolutionSpecificBuildOutputs" />
</mtbw:ProcessParameterMetadataCollection>
</this:Process.Metadata>
<this:Process.SupportedReasons>All</this:Process.SupportedReasons>
<this:Process.BuildProcessVersion>11.0</this:Process.BuildProcessVersion>
<mva:VisualBasic.Settings>Assembly references and imported namespaces serialized as XML namespaces</mva:VisualBasic.Settings>
<Sequence mtbwt:BuildTrackingParticipant.Importance="None">
<Sequence.Variables>
<Variable x:TypeArguments="mtbc:IBuildDetail" Name="BuildDetail" />
<Variable x:TypeArguments="x:String" Name="DropLocation" />
</Sequence.Variables>
<mtbwa:GetBuildDetail DisplayName="Get the Build" Result="[BuildDetail]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<Sequence DisplayName="Update Drop Location" mtbwt:BuildTrackingParticipant.Importance="Low">
<mtbwa:InvokeForReason DisplayName="Update Build Number for Triggered Builds" Reason="Triggered">
<mtbwa:UpdateBuildNumber BuildNumberFormat="[BuildNumberFormat]" DisplayName="Update Build Number" />
</mtbwa:InvokeForReason>
<If Condition="[(Not String.IsNullOrEmpty(BuildDetail.DropLocationRoot)) AndAlso (BuildDetail.Reason And Microsoft.TeamFoundation.Build.Client.BuildReason.Triggered) = BuildDetail.Reason]" DisplayName="If Build Reason is Triggered" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence mtbwt:BuildTrackingParticipant.Importance="None">
<Assign x:TypeArguments="x:String" mtbwt:BuildTrackingParticipant.Importance="None" Value="[BuildDropProvider.CombinePaths(BuildDetail.DropLocationRoot, BuildDetail.BuildDefinition.Name, BuildDetail.BuildNumber)]" To="[DropLocation]" />
<mtbwa:SetBuildProperties DisplayName="Set Drop Location" DropLocation="[DropLocation]" PropertiesToSet="DropLocation" mtbwt:BuildTrackingParticipant.Importance="Low" />
</Sequence>
</If.Then>
</If>
<If Condition="[(Not String.IsNullOrEmpty(PrivateDropLocation)) AndAlso BuildDetail.Reason = Microsoft.TeamFoundation.Build.Client.BuildReason.ValidateShelveset]" DisplayName="If Build Reason is ValidateShelveset" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence mtbwt:BuildTrackingParticipant.Importance="None">
<Assign x:TypeArguments="x:String" Value="[BuildDropProvider.CombinePaths(PrivateDropLocation, BuildDetail.BuildDefinition.Name, BuildDetail.BuildNumber)]" To="[DropLocation]" mtbwt:BuildTrackingParticipant.Importance="None" />
<mtbwa:SetBuildProperties DisplayName="Set Drop Location for Private Build" DropLocation="[DropLocation]" PropertiesToSet="DropLocation" mtbwt:BuildTrackingParticipant.Importance="Low" />
</Sequence>
</If.Then>
</If>
</Sequence>
<mtbwa:AgentScope DisplayName="Run On Agent" MaxExecutionTime="[AgentSettings.MaxExecutionTime]" MaxWaitTime="[AgentSettings.MaxWaitTime]" ReservationSpec="[AgentSettings.GetAgentReservationSpec()]">
<mtbwa:AgentScope.Variables>
<Variable x:TypeArguments="mtbc:IBuildAgent" Name="BuildAgent" />
<Variable x:TypeArguments="mtvc:Workspace" Name="Workspace" />
<Variable x:TypeArguments="x:String" Name="BuildDirectory" />
<Variable x:TypeArguments="x:String" Default="[BuildDetail.BuildNumber]" Name="LabelName" />
<Variable x:TypeArguments="x:String" Name="WorkspaceName" />
<Variable x:TypeArguments="x:String" Name="SourcesDirectory" />
<Variable x:TypeArguments="x:String" Name="BinariesDirectory" />
<Variable x:TypeArguments="x:String" Name="TestResultsDirectory" />
</mtbwa:AgentScope.Variables>
<Sequence DisplayName="Initialize Variables" mtbwt:BuildTrackingParticipant.Importance="Low">
<mtbwa:GetBuildAgent DisplayName="Get the Agent" Result="[BuildAgent]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<mtbwa:GetBuildDirectory DisplayName="Get the Build Directory" Result="[BuildDirectory]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<Assign x:TypeArguments="x:String" DisplayName="Initialize Workspace Name" To="[WorkspaceName]" Value="[String.Format(&quot;{0}_{1}_{2}&quot;, BuildDetail.BuildDefinition.Id, Microsoft.TeamFoundation.LinkingUtilities.DecodeUri(BuildAgent.Uri.AbsoluteUri).ToolSpecificId, BuildAgent.ServiceHost.Name)]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<Assign x:TypeArguments="x:String" DisplayName="Initialize Sources Directory" To="[SourcesDirectory]" Value="[String.Format(&quot;{0}\Sources&quot;, BuildDirectory)]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<Assign x:TypeArguments="x:String" DisplayName="Initialize Binaries Directory" To="[BinariesDirectory]" Value="[String.Format(&quot;{0}\Binaries&quot;, BuildDirectory)]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<Assign x:TypeArguments="x:String" DisplayName="Initialize TestResults Directory" To="[TestResultsDirectory]" Value="[String.Format(&quot;{0}\TestResults&quot;, BuildDirectory)]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<If Condition="[Not BuildSettings.HasPlatformConfigurations]" DisplayName="If Not BuildSettings.HasPlatformConfigurations" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<AddToCollection x:TypeArguments="mtbwa:PlatformConfiguration" DisplayName="Use Default Platform Configuration" Collection="[BuildSettings.PlatformConfigurations]" Item="[Microsoft.TeamFoundation.Build.Workflow.Activities.PlatformConfiguration.Default]" mtbwt:BuildTrackingParticipant.Importance="Low" />
</If.Then>
</If>
<If Condition="[WorkspaceName.Length &gt; Microsoft.TeamFoundation.VersionControl.Common.RepositoryConstants.MaxWorkspaceNameSize]" DisplayName="If WorkspaceName &gt; MaxSize" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence mtbwt:BuildTrackingParticipant.Importance="None">
<mtbwa:WriteBuildWarning DisplayName="Write Workspace Size Warning" Message="[String.Format(&quot;The workspace name '{0}' exceeds the maximum allowed limit of '{1}' characters. Truncating it to match the maximum limit.&quot;, WorkspaceName, Microsoft.TeamFoundation.VersionControl.Common.RepositoryConstants.MaxWorkspaceNameSize)]" />
<Assign x:TypeArguments="x:String" DisplayName="Truncate WorkspaceName to MaxSize" To="[WorkspaceName]" Value="[WorkspaceName.Substring(0, Microsoft.TeamFoundation.VersionControl.Common.RepositoryConstants.MaxWorkspaceNameSize).TrimEnd()]" mtbwt:BuildTrackingParticipant.Importance="Low" />
</Sequence>
</If.Then>
</If>
</Sequence>
<Sequence DisplayName="Initialize Workspace" mtbwt:BuildTrackingParticipant.Importance="Low">
<mtbwa:DeleteDirectory Directory="[TestResultsDirectory]" DisplayName="Delete Test Results Directory" Recursive="[True]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<If Condition="[Not CleanWorkspace = Microsoft.TeamFoundation.Build.Workflow.Activities.CleanWorkspaceOption.None]" DisplayName="If Not CleanWorkspace = CleanWorkspaceOption.None" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:DeleteDirectory Directory="[BinariesDirectory]" DisplayName="Delete Binaries Directory" mtbwt:BuildTrackingParticipant.Importance="Low" />
</If.Then>
</If>
<If Condition="[CleanWorkspace = Microsoft.TeamFoundation.Build.Workflow.Activities.CleanWorkspaceOption.All]" DisplayName="If CleanWorkspace = CleanWorkspaceOption.All" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence DisplayName="Delete Workspace and Sources Directory" mtbwt:BuildTrackingParticipant.Importance="Low">
<mtbwa:DeleteWorkspace DeleteLocalItems="[True]" DisplayName="Delete Workspace" Name="[WorkspaceName]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<mtbwa:DeleteDirectory Directory="[SourcesDirectory]" DisplayName="Delete Sources Directory" mtbwt:BuildTrackingParticipant.Importance="Low" />
</Sequence>
</If.Then>
</If>
<mtbwa:CreateWorkspace BuildDirectory="[BuildDirectory]" Comment="[&quot;Workspace Created by Team Build&quot;]" DisplayName="Create Workspace" Name="[WorkspaceName]" Result="[Workspace]" SourcesDirectory="[SourcesDirectory]" />
<If Condition="[CleanWorkspace = Microsoft.TeamFoundation.Build.Workflow.Activities.CleanWorkspaceOption.Outputs]" DisplayName="If CleanWorkspace = CleanWorkspaceOption.Outputs" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<ForEach x:TypeArguments="mtbwa:PlatformConfiguration" DisplayName="For Each Configuration in BuildSettings.PlatformConfigurations" Values="[BuildSettings.PlatformConfigurations]" mtbwt:BuildTrackingParticipant.Importance="Low">
<ActivityAction x:TypeArguments="mtbwa:PlatformConfiguration">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="mtbwa:PlatformConfiguration" Name="platformConfiguration" />
</ActivityAction.Argument>
<Sequence DisplayName="Clean Configuration">
<If Condition="[BuildSettings.HasProjectsToBuild]" DisplayName="If BuildSettings.HasProjectsToBuild" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<ForEach x:TypeArguments="x:String" DisplayName="For Each Project in BuildSettings.ProjectsToBuild" Values="[BuildSettings.ProjectsToBuild]" mtbwt:BuildTrackingParticipant.Importance="Low">
<ActivityAction x:TypeArguments="x:String">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="x:String" Name="serverBuildProjectItem" />
</ActivityAction.Argument>
<Sequence DisplayName="Clean Project" mtbwt:BuildTrackingParticipant.Importance="Low">
<Sequence.Variables>
<Variable x:TypeArguments="x:String" Name="localBuildProjectItem" />
</Sequence.Variables>
<mtbwa:ConvertWorkspaceItem DisplayName="Convert Server Paths to Local Paths" Input="[serverBuildProjectItem]" Result="[localBuildProjectItem]" Workspace="[Workspace]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<If Condition="[System.IO.File.Exists(localBuildProjectItem)]" DisplayName="If File.Exists(Project)" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:MSBuild CommandLineArguments="[String.Format(&quot;/p:SkipInvalidConfigurations=true {0}&quot;, MSBuildArguments)]" Configuration="[platformConfiguration.Configuration]" DisplayName="Run MSBuild for Project" GenerateVSPropsFile="[True]" MaxProcesses="[If (MSBuildMultiProc, 0, 1)]" OutDir="[BinariesDirectory]" Platform="[platformConfiguration.Platform]" Project="[localBuildProjectItem]" Targets="[New String() { &quot;Clean&quot; }]" TargetsNotLogged="[New String() {&quot;GetNativeManifest&quot;, &quot;GetCopyToOutputDirectoryItems&quot;, &quot;GetTargetPath&quot;}]" ToolPlatform="[MSBuildPlatform]" Verbosity="[Verbosity]" />
</If.Then>
</If>
</Sequence>
</ActivityAction>
</ForEach>
</If.Then>
</If>
</Sequence>
</ActivityAction>
</ForEach>
</If.Then>
</If>
<mtbwa:SyncWorkspace DisplayName="Get Workspace" VersionOverride="[GetVersion]" Workspace="[Workspace]">
<mtbwa:SyncWorkspace.RequestsFailed>
<ActivityAction x:TypeArguments="scg:ICollection(mtbc:IQueuedBuild)">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="scg:ICollection(mtbc:IQueuedBuild)" Name="failedRequests" />
</ActivityAction.Argument>
<mtbwa:RetryRequests Behavior="[Microsoft.TeamFoundation.Build.Workflow.Activities.RetryBehavior.DoNotBatch]" DisplayName="Mark Requests for Retry" Requests="[failedRequests]" mtbwt:BuildTrackingParticipant.Importance="Low" />
</ActivityAction>
</mtbwa:SyncWorkspace.RequestsFailed>
</mtbwa:SyncWorkspace>
</Sequence>
<If Condition="[CreateLabel]" DisplayName="If CreateLabel" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:InvokeForReason DisplayName="Create and Set Label for non-Shelveset Builds" Reason="Manual, IndividualCI, BatchedCI, Schedule, ScheduleForced, UserCreated">
<mtbwa:LabelWorkspace Comment="[&quot;Label Created by Team Build&quot;]" DisplayName="Create Label" Name="[LabelName]" Scope="[String.Format(&quot;$/{0}&quot;, BuildDetail.BuildDefinition.TeamProject)]" Workspace="[Workspace]" />
<mtbwa:SetBuildProperties DisplayName="Set Label on BuildDetail" LabelName="[String.Format(&quot;{0}@$/{1}&quot;, LabelName, BuildDetail.BuildDefinition.TeamProject)]" PropertiesToSet="LabelName" mtbwt:BuildTrackingParticipant.Importance="Low" />
</mtbwa:InvokeForReason>
</If.Then>
<If.Else>
<mtbwa:WriteBuildMessage DisplayName="Write Message" Message="Not Labeling sources" Importance="[Microsoft.TeamFoundation.Build.Client.BuildMessageImportance.High]" />
</If.Else>
</If>
<TryCatch DisplayName="Try Compile, Test, and Associate Changesets and Work Items" mtbwt:BuildTrackingParticipant.Importance="Low">
<TryCatch.Finally>
<Sequence DisplayName="Revert Workspace and Copy Files to Drop Location" mtbwt:BuildTrackingParticipant.Importance="Low">
<mtbwa:InvokeForReason DisplayName="Revert Workspace for Shelveset Builds" Reason="CheckInShelveset, ValidateShelveset">
<mtbwa:RevertWorkspace DisplayName="Revert Workspace" Workspace="[Workspace]" />
</mtbwa:InvokeForReason>
<If Condition="[Not String.IsNullOrEmpty(DropLocation)]" DisplayName="If DropLocation is Set" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:CopyDirectory DisplayName="Drop Files to Drop Location" Source="[BinariesDirectory]" Destination="[DropLocation]" />
</If.Then>
</If>
</Sequence>
</TryCatch.Finally>
<TryCatch.Try>
<Sequence mtbwt:BuildTrackingParticipant.Importance="None">
<Sequence.Variables>
<Variable x:TypeArguments="s:Exception" Name="compilationException" />
<Variable x:TypeArguments="scg:IList(mtvc:Changeset)" Name="associatedChangesets" />
<Variable x:TypeArguments="s:Boolean" Name="treatTestFailureAsBuildFailure" />
</Sequence.Variables>
<Parallel DisplayName="Compile, Test, and Associate Changesets and Work Items">
<TryCatch DisplayName="Try Compile and Test" mtbwt:BuildTrackingParticipant.Importance="Low">
<TryCatch.Try>
<Sequence DisplayName="Compile and Test">
<ForEach x:TypeArguments="mtbwa:PlatformConfiguration" DisplayName="For Each Configuration in BuildSettings.PlatformConfigurations" Values="[BuildSettings.PlatformConfigurations]" mtbwt:BuildTrackingParticipant.Importance="Low">
<ActivityAction x:TypeArguments="mtbwa:PlatformConfiguration">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="mtbwa:PlatformConfiguration" Name="platformConfiguration" />
</ActivityAction.Argument>
<Sequence DisplayName="Compile and Test for Configuration" mtbwt:BuildTrackingParticipant.Importance="Low">
<Sequence.Variables>
<Variable x:TypeArguments="x:String" Name="outputDirectory" />
<Variable x:TypeArguments="x:String" Name="logFileDropLocation" />
</Sequence.Variables>
<Sequence DisplayName="Initialize Variables" mtbwt:BuildTrackingParticipant.Importance="Low">
<Assign x:TypeArguments="x:String" DisplayName="Create OutputDirectory Per Platform and Configuration" To="[outputDirectory]" Value="[If (platformConfiguration.IsEmpty Or BuildSettings.PlatformConfigurations.Count = 1, BinariesDirectory, If (platformConfiguration.IsPlatformEmptyOrAnyCpu, BinariesDirectory + &quot;\&quot; + platformConfiguration.Configuration, BinariesDirectory + &quot;\&quot; + platformConfiguration.Platform + &quot;\&quot; + platformConfiguration.Configuration))]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<If Condition="[Not String.IsNullOrEmpty(DropLocation)]" DisplayName="If DropLocation is Set" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Assign x:TypeArguments="x:String" DisplayName="Initialize LogFile Drop Location" To="[logFileDropLocation]" Value="[If (platformConfiguration.IsEmpty Or BuildSettings.PlatformConfigurations.Count = 1, BuildDropProvider.CombinePaths(DropLocation, &quot;logs&quot;), If (platformConfiguration.IsPlatformEmptyOrAnyCpu, BuildDropProvider.CombinePaths(DropLocation, &quot;logs&quot;, platformConfiguration.Configuration), BuildDropProvider.CombinePaths(DropLocation, &quot;logs&quot;, platformConfiguration.Platform, platformConfiguration.Configuration)))]" mtbwt:BuildTrackingParticipant.Importance="Low" />
</If.Then>
</If>
</Sequence>
<If Condition="[BuildSettings.HasProjectsToBuild]" DisplayName="If BuildSettings.HasProjectsToBuild" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<ForEach x:TypeArguments="x:String" DisplayName="For Each Project in BuildSettings.ProjectsToBuild" Values="[BuildSettings.ProjectsToBuild]" mtbwt:BuildTrackingParticipant.Importance="Low">
<ActivityAction x:TypeArguments="x:String">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="x:String" Name="serverBuildProjectItem" />
</ActivityAction.Argument>
<TryCatch DisplayName="Try to Compile the Project" mtbwt:BuildTrackingParticipant.Importance="Low">
<TryCatch.Try>
<Sequence DisplayName="Compile the Project" mtbwt:BuildTrackingParticipant.Importance="Low">
<Sequence.Variables>
<Variable x:TypeArguments="x:String" Name="localProject" />
<Variable x:TypeArguments="x:String" Name="outputDirectoryPerProject" Default="[outputDirectory]" />
</Sequence.Variables>
<mtbwa:ConvertWorkspaceItem DisplayName="Convert Server Path to Local Path" Input="[serverBuildProjectItem]" Result="[localProject]" Workspace="[Workspace]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<If Condition="[SolutionSpecificBuildOutputs]" DisplayName="If Build Outputs are Solution-Specific" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence DisplayName="Update Output Directory" mtbwt:BuildTrackingParticipant.Importance="Low">
<Assign x:TypeArguments="x:String" DisplayName="Set Solution-Specific Output Directory" To="[outputDirectoryPerProject]" Value="[System.IO.Path.Combine(outputDirectory, System.IO.Path.GetFileNameWithoutExtension(localProject))]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<If DisplayName="If Output Directory Exists" Condition="[System.IO.Directory.Exists(outputDirectoryPerProject)]" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:WriteBuildWarning DisplayName="Write Duplicate Project Names Warning" Message="[String.Format(&quot;{0} conflicts with another solution/project. Build outputs for solutions/projects with the same name will be copied to the same directory. To separate the build outputs, change the name of one of the solutions/projects.&quot;, System.IO.Path.GetFileNameWithoutExtension(localProject))]" />
</If.Then>
</If>
</Sequence>
</If.Then>
</If>
<mtbwa:MSBuild CommandLineArguments="[String.Format(&quot;/p:SkipInvalidConfigurations=true {0}&quot;, MSBuildArguments)]" Configuration="[platformConfiguration.Configuration]" DisplayName="Run MSBuild for Project" GenerateVSPropsFile="[True]" LogFileDropLocation="[logFileDropLocation]" MaxProcesses="[If (MSBuildMultiProc, 0, 1)]" OutDir="[outputDirectoryPerProject]" Platform="[platformConfiguration.Platform]" Project="[localProject]" RunCodeAnalysis="[RunCodeAnalysis]" TargetsNotLogged="[New String() {&quot;GetNativeManifest&quot;, &quot;GetCopyToOutputDirectoryItems&quot;, &quot;GetTargetPath&quot;}]" ToolPlatform="[MSBuildPlatform]" Verbosity="[Verbosity]" />
</Sequence>
</TryCatch.Try>
<TryCatch.Catches>
<Catch x:TypeArguments="s:Exception">
<ActivityAction x:TypeArguments="s:Exception">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="s:Exception" Name="ex" />
</ActivityAction.Argument>
<Sequence DisplayName="Handle Exception">
<Sequence.Variables>
<Variable x:TypeArguments="scg:ICollection(mtbc:IQueuedBuild)" Name="failedRequests" />
</Sequence.Variables>
<mtbwa:SetBuildProperties CompilationStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Failed]" DisplayName="Set CompilationStatus to Failed" PropertiesToSet="CompilationStatus" mtbwt:BuildTrackingParticipant.Importance="Low" />
<If Condition="[CreateWorkItem]" DisplayName="If CreateWorkItem" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:InvokeForReason DisplayName="Create Work Item for non-Shelveset Builds" Reason="Manual, IndividualCI, BatchedCI, Schedule, ScheduleForced, UserCreated">
<mtbwa:OpenWorkItem AssignedTo="[BuildDetail.RequestedFor]" Comment="[&quot;This work item was created by TFS Build on a build failure.&quot;]" CustomFields="[New Dictionary(Of String, String) From { {&quot;System.Reason&quot;, &quot;Build Failure&quot;}, {&quot;Microsoft.VSTS.TCM.ReproSteps&quot;, &quot;Start the build using TFS Build&quot;}, {&quot;Priority&quot;, &quot;1&quot;}, {&quot;Severity&quot;, &quot;1 - Critical&quot;} }]" DisplayName="Create Work Item" Title="[String.Format(&quot;Build Failure in Build: {0}&quot;, BuildDetail.BuildNumber)]" Type="[&quot;Bug&quot;]" />
</mtbwa:InvokeForReason>
</If.Then>
</If>
<mtbwa:GetApprovedRequests DisplayName="Get Requests Approved for Check In" Result="[failedRequests]" mtbwt:BuildTrackingParticipant.Importance="None" />
<mtbwa:RetryRequests Behavior="[Microsoft.TeamFoundation.Build.Workflow.Activities.RetryBehavior.DoNotBatch]" DisplayName="Mark Requests for Retry" Requests="[failedRequests]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<Rethrow DisplayName="Rethrow the exception so the build will stop" mtbwt:BuildTrackingParticipant.Importance="Low" />
</Sequence>
</ActivityAction>
</Catch>
</TryCatch.Catches>
</TryCatch>
</ActivityAction>
</ForEach>
</If.Then>
</If>
<If Condition="[Not DisableTests]" DisplayName="If Not DisableTests" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence DisplayName="Run Tests" mtbwt:BuildTrackingParticipant.Importance="Low">
<If Condition="[Not TestSpecs Is Nothing]" DisplayName="If Not TestSpecs Is Nothing" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<ForEach x:TypeArguments="mtbwa:TestSpec" DisplayName="For Each TestSpec in TestSpecs" Values="[TestSpecs]" mtbwt:BuildTrackingParticipant.Importance="Low">
<ActivityAction x:TypeArguments="mtbwa:TestSpec">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="mtbwa:TestSpec" Name="spec" />
</ActivityAction.Argument>
<TryCatch DisplayName="Try Run Tests" mtbwt:BuildTrackingParticipant.Importance="Low">
<TryCatch.Try>
<If Condition="[TypeOf spec Is Microsoft.TeamFoundation.Build.Workflow.Activities.AgileTestPlatformSpec]" DisplayName="If spec Is AgileTestPlatformSpec" mtbwt:BuildTrackingParticipant.Importance="None">
<If.Then>
<Sequence DisplayName="Run Visual Studio Test Runner for Test Sources" mtbwt:BuildTrackingParticipant.Importance="Low">
<Sequence.Variables>
<Variable x:TypeArguments="mtbwa:AgileTestPlatformSpec" Name="agileTestPlatformAssembly" />
<Variable x:TypeArguments="scg:IEnumerable(x:String)" Name="agileTestPlatformAssemblies" />
</Sequence.Variables>
<Assign x:TypeArguments="mtbwa:AgileTestPlatformSpec" DisplayName="Assign spec to agileTestPlatformAssembly" To="[agileTestPlatformAssembly]" Value="[DirectCast(spec, Microsoft.TeamFoundation.Build.Workflow.Activities.AgileTestPlatformSpec)]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<mtbwa:FindMatchingFiles DisplayName="Find Visual Studio Test Platform Test Assemblies" MatchPattern="[String.Format(&quot;{0}\{1}&quot;, outputDirectory, agileTestPlatformAssembly.AssemblyFileSpec)]" Result="[agileTestPlatformAssemblies]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<If Condition="[agileTestPlatformAssemblies.Count() &gt; 0]" DisplayName="If Visual Studio Test Platform Test Assemblies Found" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<If Condition="[agileTestPlatformAssembly.HasRunSettingsFile]" DisplayName="If agileTestPlatformAssembly.HasRunSettingsFile" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence DisplayName="Find Run Settings File And Run Visual Studio Test Runner" mtbwt:BuildTrackingParticipant.Importance="Low">
<Sequence.Variables>
<Variable x:TypeArguments="x:String" Name="localRunSettings" />
</Sequence.Variables>
<mtbwa:GenerateRunSettings DisplayName="Generate Run Settings File" RunSettingsForTestRun="[agileTestPlatformAssembly.RunSettingsForTestRun]" Result="[localRunSettings]" Workspace="[Workspace]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<mtbwa:RunTests DisplayName="Run Visual Studio Test Runner for Test Sources" RunName="[agileTestPlatformAssembly.RunName]" Flavor="[platformConfiguration.Configuration]" Platform="[platformConfiguration.Platform]" TestSources="[agileTestPlatformAssemblies]" RunSettings="[localRunSettings]" TestCaseFilter="[agileTestPlatformAssembly.TestCaseFilter]" ExecutionPlatform="[agileTestPlatformAssembly.ExecutionPlatform]" />
</Sequence>
</If.Then>
<If.Else>
<mtbwa:RunTests DisplayName="Run Visual Studio Test Runner for Test Sources" RunName="[agileTestPlatformAssembly.RunName]" Flavor="[platformConfiguration.Configuration]" Platform="[platformConfiguration.Platform]" TestSources="[agileTestPlatformAssemblies]" TestCaseFilter="[agileTestPlatformAssembly.TestCaseFilter]" ExecutionPlatform="[agileTestPlatformAssembly.ExecutionPlatform]" />
</If.Else>
</If>
</If.Then>
</If>
</Sequence>
</If.Then>
<If.Else>
<If Condition="[TypeOf spec Is Microsoft.TeamFoundation.Build.Workflow.Activities.TestMetadataFileSpec]" DisplayName="If spec Is TestMetadataFileSpec" mtbwt:BuildTrackingParticipant.Importance="None">
<If.Then>
<Sequence DisplayName="Run MSTest for Metadata File">
<Sequence.Variables>
<Variable x:TypeArguments="mtbwa:TestMetadataFileSpec" Name="testMetadataFile" />
<Variable x:TypeArguments="x:String" Name="localTestMetadata" />
</Sequence.Variables>
<Assign x:TypeArguments="mtbwa:TestMetadataFileSpec" DisplayName="Assign spec to testMetadataFile" To="[testMetadataFile]" Value="[DirectCast(spec, Microsoft.TeamFoundation.Build.Workflow.Activities.TestMetadataFileSpec)]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<mtbwa:ConvertWorkspaceItem DisplayName="Convert Server Path to Local Path" Input="[testMetadataFile.MetadataFileName]" Result="[localTestMetadata]" Workspace="[Workspace]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<mtbwa:MSTest RunTitle="[testMetadataFile.RunName]" Category="[testMetadataFile.CategoryFilter]" DisplayName="Run MSTest for Metadata File" Flavor="[platformConfiguration.Configuration]" MaxPriority="[testMetadataFile.MaximumPriority]" MinPriority="[testMetadataFile.MinimumPriority]" PathToResultsFilesRoot="[TestResultsDirectory]" Platform="[platformConfiguration.Platform]" SearchPathRoot="[outputDirectory]" TestLists="[testMetadataFile.TestLists]" TestMetadata="[localTestMetadata]" TestSettings="[String.Empty]" CommandLineArguments="[testMetadataFile.MSTestCommandLineArgs]" />
</Sequence>
</If.Then>
<If.Else>
<Sequence DisplayName="Run MSTest for Test Assemblies" mtbwt:BuildTrackingParticipant.Importance="Low">
<Sequence.Variables>
<Variable x:TypeArguments="mtbwa:TestAssemblySpec" Name="testAssembly" />
<Variable x:TypeArguments="scg:IEnumerable(x:String)" Name="testAssemblies" />
<Variable x:TypeArguments="x:String" Default="[String.Empty]" Name="testFlavor" />
<Variable x:TypeArguments="x:String" Default="[String.Empty]" Name="testPlatform" />
</Sequence.Variables>
<Assign x:TypeArguments="mtbwa:TestAssemblySpec" DisplayName="Assign spec to testAssembly" To="[testAssembly]" Value="[DirectCast(spec, Microsoft.TeamFoundation.Build.Workflow.Activities.TestAssemblySpec)]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<mtbwa:FindMatchingFiles DisplayName="Find Test Assemblies" MatchPattern="[String.Format(&quot;{0}\{1}&quot;, outputDirectory, testAssembly.AssemblyFileSpec)]" Result="[testAssemblies]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<If Condition="[testAssemblies.Count() &gt; 0]" DisplayName="If Test Assemblies Found" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<If Condition="[testAssembly.HasTestSettingsFile]" DisplayName="If testAssembly.HasTestSettingsFile" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence DisplayName="Find Test Settings File And Run MSTest" mtbwt:BuildTrackingParticipant.Importance="Low">
<Sequence.Variables>
<Variable x:TypeArguments="x:String" Name="localTestSettings" />
</Sequence.Variables>
<mtbwa:ConvertWorkspaceItem DisplayName="Convert Server Path to Local Path" Input="[testAssembly.TestSettingsFileName]" Result="[localTestSettings]" Workspace="[Workspace]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<mtbwa:MSTest RunTitle="[testAssembly.RunName]" Category="[testAssembly.CategoryFilter]" DisplayName="Run MSTest for Test Assemblies" Flavor="[platformConfiguration.Configuration]" MaxPriority="[testAssembly.MaximumPriority]" MinPriority="[testAssembly.MinimumPriority]" PathToResultsFilesRoot="[TestResultsDirectory]" Platform="[platformConfiguration.Platform]" SearchPathRoot="[outputDirectory]" TestContainers="[testAssemblies]" TestSettings="[localTestSettings]" CommandLineArguments="[testAssembly.MSTestCommandLineArgs]" />
</Sequence>
</If.Then>
<If.Else>
<mtbwa:MSTest RunTitle="[testAssembly.RunName]" Category="[testAssembly.CategoryFilter]" DisplayName="Run MSTest for Test Assemblies" Flavor="[platformConfiguration.Configuration]" MaxPriority="[testAssembly.MaximumPriority]" MinPriority="[testAssembly.MinimumPriority]" PathToResultsFilesRoot="[TestResultsDirectory]" Platform="[platformConfiguration.Platform]" SearchPathRoot="[outputDirectory]" TestContainers="[testAssemblies]" CommandLineArguments="[testAssembly.MSTestCommandLineArgs]" />
</If.Else>
</If>
</If.Then>
</If>
</Sequence>
</If.Else>
</If>
</If.Else>
</If>
</TryCatch.Try>
<TryCatch.Catches>
<Catch x:TypeArguments="s:Exception">
<ActivityAction x:TypeArguments="s:Exception">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="s:Exception" Name="testException" />
</ActivityAction.Argument>
<Sequence DisplayName="Handle Test Run Exception">
<Sequence.Variables>
<Variable x:TypeArguments="scg:ICollection(mtbc:IQueuedBuild)" Name="failedRequests" />
</Sequence.Variables>
<If Condition="[Not (TypeOf testException Is Microsoft.TeamFoundation.Build.Workflow.Activities.TestFailureException)]" DisplayName="If testException is NOT TestFailureException" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:WriteBuildError DisplayName="Write Test Failure Message" Message="[testException.Message]" />
</If.Then>
</If>
<mtbwa:SetBuildProperties DisplayName="Set TestStatus to Failed" PropertiesToSet="TestStatus" TestStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Failed]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<If Condition="[spec.FailBuildOnFailure]" DisplayName="If spec.FailBuildOnFailure" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Assign x:TypeArguments="s:Boolean" DisplayName="Set treatTestFailureAsBuildFailure to True" To="[treatTestFailureAsBuildFailure]" Value="[True]" mtbwt:BuildTrackingParticipant.Importance="Low" />
</If.Then>
</If>
<mtbwa:GetApprovedRequests DisplayName="Get Requests Approved for Check In" Result="[failedRequests]" mtbwt:BuildTrackingParticipant.Importance="None" />
<mtbwa:RetryRequests Behavior="[Microsoft.TeamFoundation.Build.Workflow.Activities.RetryBehavior.DoNotBatch]" DisplayName="Mark Requests for Retry" Requests="[failedRequests]" mtbwt:BuildTrackingParticipant.Importance="Low" />
</Sequence>
</ActivityAction>
</Catch>
</TryCatch.Catches>
</TryCatch>
</ActivityAction>
</ForEach>
</If.Then>
</If>
</Sequence>
</If.Then>
<If.Else>
<If Condition="[(Not TestSpecs Is Nothing) And (TestSpecs.Count > 0)]" DisplayName="If TestSpecs Is Not Nothing or Empty" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:WriteBuildWarning DisplayName="Write Warning" Message="No automated tests will be run for this build because tests have been disabled for this build definition. To enable these tests, edit this build definition and set the Disable Tests process parameter to false." />
</If.Then>
</If>
</If.Else>
</If>
</Sequence>
</ActivityAction>
</ForEach>
<If Condition="[BuildDetail.CompilationStatus = Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Unknown]" DisplayName="If CompilationStatus = Unknown" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:SetBuildProperties CompilationStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Succeeded]" DisplayName="Set CompilationStatus to Succeeded" PropertiesToSet="CompilationStatus" mtbwt:BuildTrackingParticipant.Importance="Low" />
</If.Then>
</If>
<If Condition="[BuildDetail.TestStatus = Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Unknown]" DisplayName="If TestStatus = Unknown" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:SetBuildProperties DisplayName="Set TestStatus to Succeeded" PropertiesToSet="TestStatus" TestStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Succeeded]" mtbwt:BuildTrackingParticipant.Importance="Low" />
</If.Then>
</If>
<If Condition="[treatTestFailureAsBuildFailure And (BuildDetail.TestStatus = Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Failed)]" DisplayName="If TreatTestFailureAsBuildFailure And (TestStatus = Failed)" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:SetBuildProperties DisplayName="Set Status to Failed" PropertiesToSet="Status" Status="[Microsoft.TeamFoundation.Build.Client.BuildStatus.Failed]" mtbwt:BuildTrackingParticipant.Importance="Low" />
</If.Then>
</If>
</Sequence>
</TryCatch.Try>
<TryCatch.Catches>
<Catch x:TypeArguments="s:Exception">
<ActivityAction x:TypeArguments="s:Exception">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="s:Exception" Name="compilationExceptionArgument" />
</ActivityAction.Argument>
<Assign x:TypeArguments="s:Exception" DisplayName="Save the Compilation Exception" To="[compilationException]" Value="[compilationExceptionArgument]" mtbwt:BuildTrackingParticipant.Importance="None" />
</ActivityAction>
</Catch>
</TryCatch.Catches>
</TryCatch>
<If Condition="[AssociateChangesetsAndWorkItems]" DisplayName="If AssociateChangesetsAndWorkItems" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<If Condition="[CreateLabel]" DisplayName="If CreateLabel and AssociateChangesetsAndWorkItems" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:InvokeForReason DisplayName="Associate Changesets and Work Items for non-Shelveset Builds" Reason="Manual, IndividualCI, BatchedCI, Schedule, ScheduleForced, UserCreated">
<mtbwa:AssociateChangesetsAndWorkItems DisplayName="Associate Changesets and Work Items" Result="[associatedChangesets]" />
</mtbwa:InvokeForReason>
</If.Then>
<If.Else>
<mtbwa:WriteBuildWarning DisplayName="Write Associate Changesets and Work Items Warning" Message="Cannot Associate Changesets and Work Items because the Label Sources option is set to False." />
</If.Else>
</If>
</If.Then>
</If>
</Parallel>
<If Condition="[Not compilationException Is Nothing]" DisplayName="If a Compilation Exception Occurred" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Throw DisplayName="Rethrow Compilation Exception" Exception="[compilationException]" mtbwt:BuildTrackingParticipant.Importance="Low" />
</If.Then>
</If>
<Parallel DisplayName="Get Impacted Tests, Index Sources and Publish Symbols">
<If Condition="[PerformTestImpactAnalysis]" DisplayName="If PerformTestImpactAnalysis" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence DisplayName="Get Impacted Tests" mtbwt:BuildTrackingParticipant.Importance="Low">
<Sequence.Variables>
<Variable x:TypeArguments="scg:IEnumerable(x:String)" Name="assemblies" />
</Sequence.Variables>
<mtbwa:FindMatchingFiles DisplayName="Find Build Outputs" MatchPattern="[String.Format(&quot;{0}\**\*.dll;{0}\**\*.exe&quot;, BinariesDirectory)]" Result="[assemblies]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<mttbb:GetImpactedTests Assemblies="[assemblies]" AssociatedChangesets="[associatedChangesets]" BinariesRoot="[BinariesDirectory]" Build="[BuildDetail]" CodeChanges="{x:Null}" DisplayName="Get Impacted Tests" ImpactedTests="{x:Null}" Workspace="[Workspace]" />
</Sequence>
</If.Then>
</If>
<If Condition="[SourceAndSymbolServerSettings.IndexSources Or SourceAndSymbolServerSettings.HasSymbolStorePath]" DisplayName="If SourceAndSymbolServerSettings.IndexSources Or SourceAndSymbolServerSettings.HasSymbolStorePath" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:InvokeForReason DisplayName="Index Sources and Publish Symbols for Triggered Builds" Reason="Triggered">
<mtbwa:InvokeForReason.Variables>
<Variable x:TypeArguments="scg:IEnumerable(x:String)" Name="symbolFiles" />
</mtbwa:InvokeForReason.Variables>
<mtbwa:FindMatchingFiles DisplayName="Find Symbol Files" MatchPattern="[String.Format(&quot;{0}\**\*.pdb&quot;, BinariesDirectory)]" Result="[symbolFiles]" mtbwt:BuildTrackingParticipant.Importance="Low" />
<If Condition="[SourceAndSymbolServerSettings.IndexSources]" DisplayName="If SourceAndSymbolServerSettings.IndexSources" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<TryCatch DisplayName="Try Index Sources" mtbwt:BuildTrackingParticipant.Importance="Low">
<TryCatch.Try>
<mtbwa:IndexSources DisplayName="Index Sources" FileList="[symbolFiles]" />
</TryCatch.Try>
<TryCatch.Catches>
<Catch x:TypeArguments="s:Exception">
<ActivityAction x:TypeArguments="s:Exception">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="s:Exception" Name="exception" />
</ActivityAction.Argument>
<mtbwa:WriteBuildError DisplayName="Write Indexing Sources Error" Message="[exception.Message]" />
</ActivityAction>
</Catch>
</TryCatch.Catches>
</TryCatch>
</If.Then>
</If>
<If Condition="[SourceAndSymbolServerSettings.HasSymbolStorePath]" DisplayName="If SourceAndSymbolServerSettings.HasSymbolStorePath" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<TryCatch DisplayName="Try Publish Symbols" mtbwt:BuildTrackingParticipant.Importance="Low">
<TryCatch.Try>
<mtbwa:SharedResourceScope DisplayName="Synchronize Access to Symbol Store" MaxExecutionTime="[TimeSpan.Zero]" MaxWaitTime="[New TimeSpan(1, 0, 0)]" ResourceName="[SourceAndSymbolServerSettings.SymbolStorePath]" mtbwt:BuildTrackingParticipant.Importance="Low">
<mtbwa:PublishSymbols DisplayName="Publish Symbols" FileList="[symbolFiles]" ProductName="[BuildDetail.BuildDefinition.Name]" StorePath="[SourceAndSymbolServerSettings.SymbolStorePath]" Version="[BuildDetail.BuildNumber]" />
</mtbwa:SharedResourceScope>
</TryCatch.Try>
<TryCatch.Catches>
<Catch x:TypeArguments="s:Exception">
<ActivityAction x:TypeArguments="s:Exception">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="s:Exception" Name="exception" />
</ActivityAction.Argument>
<mtbwa:WriteBuildError DisplayName="Write Publishing Symbols Error" Message="[exception.Message]" />
</ActivityAction>
</Catch>
</TryCatch.Catches>
</TryCatch>
</If.Then>
</If>
</mtbwa:InvokeForReason>
</If.Then>
</If>
</Parallel>
</Sequence>
</TryCatch.Try>
</TryCatch>
</mtbwa:AgentScope>
<mtbwa:InvokeForReason DisplayName="Check In Gated Changes for CheckInShelveset Builds" Reason="CheckInShelveset">
<mtbwa:CheckInGatedChanges DisplayName="Check In Gated Changes" />
</mtbwa:InvokeForReason>
</Sequence>
</Activity>

+ 0
- 602
BuildProcessTemplates/DefaultTemplate.xaml View File

@@ -1,602 +0,0 @@
<Activity mc:Ignorable="sap" x:Class="TfsBuild.Process" this:Process.BuildSettings="[New Microsoft.TeamFoundation.Build.Workflow.Activities.BuildSettings()]" this:Process.TestSpecs="[New Microsoft.TeamFoundation.Build.Workflow.Activities.TestSpecList(New Microsoft.TeamFoundation.Build.Workflow.Activities.TestAssemblySpec(&quot;**\*test*.dll&quot;))]" this:Process.BuildNumberFormat="[&quot;$(BuildDefinitionName)_$(Date:yyyyMMdd)$(Rev:.r)&quot;]" this:Process.CleanWorkspace="[Microsoft.TeamFoundation.Build.Workflow.Activities.CleanWorkspaceOption.All]" this:Process.RunCodeAnalysis="[Microsoft.TeamFoundation.Build.Workflow.Activities.CodeAnalysisOption.AsConfigured]" this:Process.SourceAndSymbolServerSettings="[New Microsoft.TeamFoundation.Build.Workflow.Activities.SourceAndSymbolServerSettings(True, Nothing)]" this:Process.AgentSettings="[New Microsoft.TeamFoundation.Build.Workflow.Activities.AgentSettings() With {.MaxWaitTime = New System.TimeSpan(4, 0, 0), .MaxExecutionTime = New System.TimeSpan(0, 0, 0), .TagComparison = Microsoft.TeamFoundation.Build.Workflow.Activities.TagComparison.MatchExactly }]" this:Process.AssociateChangesetsAndWorkItems="[True]" this:Process.CreateWorkItem="[True]" this:Process.DropBuild="[True]" this:Process.MSBuildPlatform="[Microsoft.TeamFoundation.Build.Workflow.Activities.ToolPlatform.Auto]" this:Process.PerformTestImpactAnalysis="[True]" this:Process.CreateLabel="[True]" this:Process.DisableTests="[False]" this:Process.Verbosity="[Microsoft.TeamFoundation.Build.Workflow.BuildVerbosity.Normal]" this:Process.SupportedReasons="All" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mt="clr-namespace:Microsoft.TeamFoundation;assembly=Microsoft.TeamFoundation.Common" xmlns:mtbc="clr-namespace:Microsoft.TeamFoundation.Build.Client;assembly=Microsoft.TeamFoundation.Build.Client" xmlns:mtbw="clr-namespace:Microsoft.TeamFoundation.Build.Workflow;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtbwa="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Activities;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtbwt="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Tracking;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mttbb="clr-namespace:Microsoft.TeamFoundation.TestImpact.BuildIntegration.BuildActivities;assembly=Microsoft.TeamFoundation.TestImpact.BuildIntegration" xmlns:mtvc="clr-namespace:Microsoft.TeamFoundation.VersionControl.Client;assembly=Microsoft.TeamFoundation.VersionControl.Client" xmlns:mtvc1="clr-namespace:Microsoft.TeamFoundation.VersionControl.Common;assembly=Microsoft.TeamFoundation.VersionControl.Common" xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:sa="clr-namespace:System.Activities;assembly=System.Activities" xmlns:sad="clr-namespace:System.Activities.Debugger;assembly=System.Activities" xmlns:sap="http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib" xmlns:si="clr-namespace:System.IO;assembly=mscorlib" xmlns:sl="clr-namespace:System.Linq;assembly=System.Core" xmlns:this="clr-namespace:TfsBuild" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<x:Members>
<x:Property Name="BuildSettings" Type="InArgument(mtbwa:BuildSettings)" />
<x:Property Name="TestSpecs" Type="InArgument(mtbwa:TestSpecList)" />
<x:Property Name="BuildNumberFormat" Type="InArgument(x:String)" />
<x:Property Name="CleanWorkspace" Type="InArgument(mtbwa:CleanWorkspaceOption)" />
<x:Property Name="RunCodeAnalysis" Type="InArgument(mtbwa:CodeAnalysisOption)" />
<x:Property Name="SourceAndSymbolServerSettings" Type="InArgument(mtbwa:SourceAndSymbolServerSettings)" />
<x:Property Name="AgentSettings" Type="InArgument(mtbwa:AgentSettings)" />
<x:Property Name="AssociateChangesetsAndWorkItems" Type="InArgument(x:Boolean)" />
<x:Property Name="CreateWorkItem" Type="InArgument(x:Boolean)" />
<x:Property Name="DropBuild" Type="InArgument(x:Boolean)" />
<x:Property Name="MSBuildArguments" Type="InArgument(x:String)" />
<x:Property Name="MSBuildPlatform" Type="InArgument(mtbwa:ToolPlatform)" />
<x:Property Name="PerformTestImpactAnalysis" Type="InArgument(x:Boolean)" />
<x:Property Name="CreateLabel" Type="InArgument(x:Boolean)" />
<x:Property Name="DisableTests" Type="InArgument(x:Boolean)" />
<x:Property Name="GetVersion" Type="InArgument(x:String)" />
<x:Property Name="PrivateDropLocation" Type="InArgument(x:String)" />
<x:Property Name="Verbosity" Type="InArgument(mtbw:BuildVerbosity)" />
<x:Property Name="Metadata" Type="mtbw:ProcessParameterMetadataCollection" />
<x:Property Name="SupportedReasons" Type="mtbc:BuildReason" />
</x:Members>
<this:Process.MSBuildArguments>
<InArgument x:TypeArguments="x:String" />
</this:Process.MSBuildArguments>
<this:Process.GetVersion>
<InArgument x:TypeArguments="x:String" />
</this:Process.GetVersion>
<this:Process.Metadata>
<mtbw:ProcessParameterMetadataCollection />
</this:Process.Metadata>
<mva:VisualBasic.Settings>Assembly references and imported namespaces serialized as XML namespaces</mva:VisualBasic.Settings>
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="ShouldExpandAll">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<Sequence sad:XamlDebuggerXmlReader.FileName="C:\vstf\lab26vsts\src\vset\SCM\BigBuild\templates\defaulttemplate.xaml" sap:VirtualizedContainerService.HintSize="1972,13038" mtbwt:BuildTrackingParticipant.Importance="None">
<Sequence.Variables>
<Variable x:TypeArguments="mtbc:IBuildDetail" Name="BuildDetail" />
</Sequence.Variables>
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtbwa:GetBuildDetail DisplayName="Get the Build" sap:VirtualizedContainerService.HintSize="1950,22" mtbwt:BuildTrackingParticipant.Importance="Low" Result="[BuildDetail]" />
<Sequence DisplayName="Update Drop Location" sap:VirtualizedContainerService.HintSize="1950,1310" mtbwt:BuildTrackingParticipant.Importance="Low">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtbwa:InvokeForReason DisplayName="Update Build Number for Triggered Builds" sap:VirtualizedContainerService.HintSize="611,146" Reason="Triggered">
<mtbwa:UpdateBuildNumber BuildNumberFormat="[BuildNumberFormat]" DisplayName="Update Build Number" sap:VirtualizedContainerService.HintSize="200,22" />
</mtbwa:InvokeForReason>
<If Condition="[DropBuild AndAlso (BuildDetail.Reason And Microsoft.TeamFoundation.Build.Client.BuildReason.Triggered) = BuildDetail.Reason]" DisplayName="If DropBuild And Build Reason is Triggered" sap:VirtualizedContainerService.HintSize="611,550" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence sap:VirtualizedContainerService.HintSize="486,449" mtbwt:BuildTrackingParticipant.Importance="None">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<If Condition="[String.IsNullOrEmpty(BuildDetail.DropLocationRoot)]" DisplayName="If DropLocationRoot is empty" sap:VirtualizedContainerService.HintSize="464,201" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Throw DisplayName="Throw EmptyDropLocationRootException" Exception="[New Microsoft.TeamFoundation.Build.Workflow.Activities.EmptyDropLocationRootException(BuildDetail.BuildDefinition.Name)]" sap:VirtualizedContainerService.HintSize="269,100" mtbwt:BuildTrackingParticipant.Importance="Low" />
</If.Then>
</If>
<mtbwa:SetBuildProperties DisplayName="Set Drop Location" DropLocation="[BuildDetail.DropLocationRoot + &quot;\&quot; + BuildDetail.BuildDefinition.Name + &quot;\&quot; + BuildDetail.BuildNumber]" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Low" PropertiesToSet="DropLocation" />
<mtbwa:CreateDirectory Directory="[BuildDetail.DropLocation]" DisplayName="Create the Drop Location" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Normal" />
</Sequence>
</If.Then>
</If>
<If Condition="[DropBuild AndAlso BuildDetail.Reason = Microsoft.TeamFoundation.Build.Client.BuildReason.ValidateShelveset]" DisplayName="If DropBuild And Build Reason is ValidateShelveset" sap:VirtualizedContainerService.HintSize="611,410" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<If Condition="[Not String.IsNullOrEmpty(PrivateDropLocation)]" sap:VirtualizedContainerService.HintSize="464,309" mtbwt:BuildTrackingParticipant.Importance="None">
<If.Then>
<Sequence sap:VirtualizedContainerService.HintSize="231,208" mtbwt:BuildTrackingParticipant.Importance="None">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtbwa:SetBuildProperties DisplayName="Set Drop Location for Private Build" DropLocation="[PrivateDropLocation + &quot;\&quot; + BuildDetail.BuildDefinition.Name + &quot;\&quot; + BuildDetail.BuildNumber]" sap:VirtualizedContainerService.HintSize="200,22" mtbwt:BuildTrackingParticipant.Importance="Low" PropertiesToSet="DropLocation" />
<mtbwa:CreateDirectory Directory="[BuildDetail.DropLocation]" DisplayName="Create the Drop Location" sap:VirtualizedContainerService.HintSize="200,22" mtbwt:BuildTrackingParticipant.Importance="Normal" />
</Sequence>
</If.Then>
<If.Else>
<mtbwa:WriteBuildWarning sap:VirtualizedContainerService.HintSize="208,208" Message="The build outputs for this private build will not be copied to the drop location because the PrivateDropLocation is not set." />
</If.Else>
</If>
</If.Then>
</If>
</Sequence>
<mtbwa:AgentScope DisplayName="Run On Agent" sap:VirtualizedContainerService.HintSize="1950,11316" MaxExecutionTime="[AgentSettings.MaxExecutionTime]" MaxWaitTime="[AgentSettings.MaxWaitTime]" ReservationSpec="[AgentSettings.GetAgentReservationSpec()]">
<mtbwa:AgentScope.Variables>
<Variable x:TypeArguments="mtbc:IBuildAgent" Name="BuildAgent" />
<Variable x:TypeArguments="mtvc:Workspace" Name="Workspace" />
<Variable x:TypeArguments="x:String" Name="BuildDirectory" />
<Variable x:TypeArguments="x:String" Default="[BuildDetail.BuildNumber]" Name="LabelName" />
<Variable x:TypeArguments="x:String" Name="WorkspaceName" />
<Variable x:TypeArguments="x:String" Name="SourcesDirectory" />
<Variable x:TypeArguments="x:String" Name="BinariesDirectory" />
<Variable x:TypeArguments="x:String" Name="TestResultsDirectory" />
</mtbwa:AgentScope.Variables>
<Sequence DisplayName="Initialize Variables" sap:VirtualizedContainerService.HintSize="1928,1046" mtbwt:BuildTrackingParticipant.Importance="Low">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtbwa:GetBuildAgent DisplayName="Get the Agent" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Low" Result="[BuildAgent]" />
<mtbwa:GetBuildDirectory DisplayName="Get the Build Directory" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Low" Result="[BuildDirectory]" />
<Assign x:TypeArguments="x:String" DisplayName="Initialize Workspace Name" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Low" To="[WorkspaceName]" Value="[String.Format(&quot;{0}_{1}_{2}&quot;, BuildDetail.BuildDefinition.Id, Microsoft.TeamFoundation.LinkingUtilities.DecodeUri(BuildAgent.Uri.AbsoluteUri).ToolSpecificId, BuildAgent.ServiceHost.Name)]" />
<Assign x:TypeArguments="x:String" DisplayName="Initialize Sources Directory" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Low" To="[SourcesDirectory]" Value="[String.Format(&quot;{0}\Sources&quot;, BuildDirectory)]" />
<Assign x:TypeArguments="x:String" DisplayName="Initialize Binaries Directory" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Low" To="[BinariesDirectory]" Value="[String.Format(&quot;{0}\Binaries&quot;, BuildDirectory)]" />
<Assign x:TypeArguments="x:String" DisplayName="Initialize TestResults Directory" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Low" To="[TestResultsDirectory]" Value="[String.Format(&quot;{0}\TestResults&quot;, BuildDirectory)]" />
<If Condition="[Not BuildSettings.HasPlatformConfigurations]" DisplayName="If Not BuildSettings.HasPlatformConfigurations" sap:VirtualizedContainerService.HintSize="464,201" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<AddToCollection x:TypeArguments="mtbwa:PlatformConfiguration" DisplayName="Use Default Platform Configuration" Collection="[BuildSettings.PlatformConfigurations]" Item="[Microsoft.TeamFoundation.Build.Workflow.Activities.PlatformConfiguration.Default]" mtbwt:BuildTrackingParticipant.Importance="Low" />
</If.Then>
</If>
<If Condition="[WorkspaceName.Length &gt; Microsoft.TeamFoundation.VersionControl.Common.RepositoryConstants.MaxWorkspaceNameSize]" DisplayName="If WorkspaceName &gt; MaxSize" sap:VirtualizedContainerService.HintSize="464,309" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence sap:VirtualizedContainerService.HintSize="281,208" mtbwt:BuildTrackingParticipant.Importance="None">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtbwa:WriteBuildWarning sap:VirtualizedContainerService.HintSize="200,22" Message="[String.Format(&quot;The workspace name '{0}' exceeds the maximum allowed limit of '{1}' characters. Truncating it to match the maximum limit.&quot;, WorkspaceName, Microsoft.TeamFoundation.VersionControl.Common.RepositoryConstants.MaxWorkspaceNameSize)]" />
<Assign x:TypeArguments="x:String" DisplayName="Truncate WorkspaceName to MaxSize" sap:VirtualizedContainerService.HintSize="200,22" mtbwt:BuildTrackingParticipant.Importance="Low" To="[WorkspaceName]" Value="[WorkspaceName.Substring(0, Microsoft.TeamFoundation.VersionControl.Common.RepositoryConstants.MaxWorkspaceNameSize).TrimEnd()]" />
</Sequence>
</If.Then>
</If>
</Sequence>
<Sequence DisplayName="Initialize Workspace" sap:VirtualizedContainerService.HintSize="1928,1819" mtbwt:BuildTrackingParticipant.Importance="Low">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtbwa:DeleteDirectory Directory="[TestResultsDirectory]" DisplayName="Delete Test Results Directory" sap:VirtualizedContainerService.HintSize="818,22" mtbwt:BuildTrackingParticipant.Importance="Normal" Recursive="[True]" />
<If Condition="[Not CleanWorkspace = Microsoft.TeamFoundation.Build.Workflow.Activities.CleanWorkspaceOption.None]" DisplayName="If Not CleanWorkspace = CleanWorkspaceOption.None" sap:VirtualizedContainerService.HintSize="818,201" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:DeleteDirectory Directory="[BinariesDirectory]" DisplayName="Delete Binaries Directory" sap:VirtualizedContainerService.HintSize="269,100" mtbwt:BuildTrackingParticipant.Importance="Normal" />
</If.Then>
</If>
<If Condition="[CleanWorkspace = Microsoft.TeamFoundation.Build.Workflow.Activities.CleanWorkspaceOption.All]" DisplayName="If CleanWorkspace = CleanWorkspaceOption.All" sap:VirtualizedContainerService.HintSize="818,309" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence DisplayName="Delete Workspace and Sources Directory" sap:VirtualizedContainerService.HintSize="281,208" mtbwt:BuildTrackingParticipant.Importance="Low">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtbwa:DeleteWorkspace DeleteLocalItems="[True]" DisplayName="Delete Workspace" sap:VirtualizedContainerService.HintSize="200,22" mtbwt:BuildTrackingParticipant.Importance="Normal" Name="[WorkspaceName]" />
<mtbwa:DeleteDirectory Directory="[SourcesDirectory]" DisplayName="Delete Sources Directory" sap:VirtualizedContainerService.HintSize="200,22" mtbwt:BuildTrackingParticipant.Importance="Normal" />
</Sequence>
</If.Then>
</If>
<mtbwa:CreateWorkspace BuildDirectory="[BuildDirectory]" Comment="[&quot;Workspace Created by Team Build&quot;]" DisplayName="Create Workspace" sap:VirtualizedContainerService.HintSize="818,22" Name="[WorkspaceName]" Result="[Workspace]" SourcesDirectory="[SourcesDirectory]" />
<If Condition="[CleanWorkspace = Microsoft.TeamFoundation.Build.Workflow.Activities.CleanWorkspaceOption.Outputs]" DisplayName="If CleanWorkspace = CleanWorkspaceOption.Outputs" sap:VirtualizedContainerService.HintSize="818,919" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<ForEach x:TypeArguments="mtbwa:PlatformConfiguration" DisplayName="For Each Configuration in BuildSettings.PlatformConfigurations" sap:VirtualizedContainerService.HintSize="693,818" mtbwt:BuildTrackingParticipant.Importance="Low" Values="[BuildSettings.PlatformConfigurations]">
<ActivityAction x:TypeArguments="mtbwa:PlatformConfiguration">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="mtbwa:PlatformConfiguration" Name="platformConfiguration" />
</ActivityAction.Argument>
<Sequence DisplayName="Clean Configuration" sap:VirtualizedContainerService.HintSize="663,715">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<If Condition="[BuildSettings.HasProjectsToBuild]" DisplayName="If BuildSettings.HasProjectsToBuild" sap:VirtualizedContainerService.HintSize="641,591" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<ForEach x:TypeArguments="x:String" DisplayName="For Each Project in BuildSettings.ProjectsToBuild" sap:VirtualizedContainerService.HintSize="516,490" mtbwt:BuildTrackingParticipant.Importance="Low" Values="[BuildSettings.ProjectsToBuild]">
<ActivityAction x:TypeArguments="x:String">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="x:String" Name="serverBuildProjectItem" />
</ActivityAction.Argument>
<Sequence DisplayName="Clean Project" sap:VirtualizedContainerService.HintSize="486,387" mtbwt:BuildTrackingParticipant.Importance="Normal">
<Sequence.Variables>
<Variable x:TypeArguments="x:String" Name="localBuildProjectItem" />
</Sequence.Variables>
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtbwa:ConvertWorkspaceItem DisplayName="Convert Server Paths to Local Paths" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Low" Input="[serverBuildProjectItem]" Result="[localBuildProjectItem]" Workspace="[Workspace]" />
<If Condition="[System.IO.File.Exists(localBuildProjectItem)]" DisplayName="If File.Exists(Project)" sap:VirtualizedContainerService.HintSize="464,201" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:MSBuild CommandLineArguments="[String.Format(&quot;/p:SkipInvalidConfigurations=true {0}&quot;, MSBuildArguments)]" Configuration="[platformConfiguration.Configuration]" DisplayName="Run MSBuild for Project" GenerateVSPropsFile="[True]" sap:VirtualizedContainerService.HintSize="269,100" OutDir="[BinariesDirectory]" Platform="[platformConfiguration.Platform]" Project="[localBuildProjectItem]" Targets="[New String() { &quot;Clean&quot; }]" TargetsNotLogged="[New String() {&quot;GetNativeManifest&quot;, &quot;GetCopyToOutputDirectoryItems&quot;, &quot;GetTargetPath&quot;}]" ToolPlatform="[MSBuildPlatform]" Verbosity="[Verbosity]" />
</If.Then>
</If>
</Sequence>
</ActivityAction>
</ForEach>
</If.Then>
</If>
</Sequence>
</ActivityAction>
</ForEach>
</If.Then>
</If>
<mtbwa:SyncWorkspace DisplayName="Get Workspace" sap:VirtualizedContainerService.HintSize="818,22" VersionOverride="[GetVersion]" Workspace="[Workspace]" />
</Sequence>
<If Condition="[CreateLabel]" DisplayName="If CreateLabel" sap:VirtualizedContainerService.HintSize="1928,309" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:InvokeForReason DisplayName="Create and Set Label for non-Shelveset Builds" sap:VirtualizedContainerService.HintSize="281,208" Reason="Manual, IndividualCI, BatchedCI, Schedule, ScheduleForced, UserCreated">
<mtbwa:LabelWorkspace Comment="[&quot;Label Created by Team Build&quot;]" DisplayName="Create Label" sap:VirtualizedContainerService.HintSize="200,22" Name="[LabelName]" Scope="[String.Format(&quot;$/{0}&quot;, BuildDetail.BuildDefinition.TeamProject)]" Workspace="[Workspace]" />
<mtbwa:SetBuildProperties DisplayName="Set Label on BuildDetail" sap:VirtualizedContainerService.HintSize="200,22" mtbwt:BuildTrackingParticipant.Importance="Low" LabelName="[String.Format(&quot;{0}@$/{1}&quot;, LabelName, BuildDetail.BuildDefinition.TeamProject)]" PropertiesToSet="LabelName" />
</mtbwa:InvokeForReason>
</If.Then>
</If>
<TryCatch DisplayName="Try Compile, Test, and Associate Changesets and Work Items" sap:VirtualizedContainerService.HintSize="1928,7898" mtbwt:BuildTrackingParticipant.Importance="Low">
<TryCatch.Finally>
<Sequence DisplayName="Revert Workspace and Copy Files to Drop Location" sap:VirtualizedContainerService.HintSize="1910,511" mtbwt:BuildTrackingParticipant.Importance="Low">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtbwa:InvokeForReason DisplayName="Revert Workspace for Shelveset Builds" sap:VirtualizedContainerService.HintSize="464,146" Reason="ValidateShelveset, CheckInShelveset">
<mtbwa:RevertWorkspace DisplayName="Revert Workspace" sap:VirtualizedContainerService.HintSize="200,22" Workspace="[Workspace]" />
</mtbwa:InvokeForReason>
<If Condition="[DropBuild AndAlso Not String.IsNullOrEmpty(BuildDetail.DropLocation)]" DisplayName="If DropBuild And DropLocation is Set" sap:VirtualizedContainerService.HintSize="464,201" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:CopyDirectory Destination="[BuildDetail.DropLocation]" DisplayName="Copy Files to Drop Location" sap:VirtualizedContainerService.HintSize="269,100" Source="[BinariesDirectory]" />
</If.Then>
</If>
</Sequence>
</TryCatch.Finally>
<TryCatch.Try>
<Sequence sap:VirtualizedContainerService.HintSize="1910,7226" mtbwt:BuildTrackingParticipant.Importance="None">
<Sequence.Variables>
<Variable x:TypeArguments="s:Exception" Name="compilationException" />
<Variable x:TypeArguments="scg:IList(mtvc:Changeset)" Name="associatedChangesets" />
<Variable x:TypeArguments="x:Boolean" Name="treatTestFailureAsBuildFailure" />
</Sequence.Variables>
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<Parallel DisplayName="Compile, Test, and Associate Changesets and Work Items" sap:VirtualizedContainerService.HintSize="1888,5264">
<TryCatch DisplayName="Try Compile and Test" sap:VirtualizedContainerService.HintSize="1270,5218" mtbwt:BuildTrackingParticipant.Importance="Low">
<TryCatch.Try>
<Sequence DisplayName="Compile and Test" sap:VirtualizedContainerService.HintSize="1252,4850">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<ForEach x:TypeArguments="mtbwa:PlatformConfiguration" DisplayName="For Each Configuration in BuildSettings.PlatformConfigurations" sap:VirtualizedContainerService.HintSize="1230,4003" mtbwt:BuildTrackingParticipant.Importance="Low" Values="[BuildSettings.PlatformConfigurations]">
<ActivityAction x:TypeArguments="mtbwa:PlatformConfiguration">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="mtbwa:PlatformConfiguration" Name="platformConfiguration" />
</ActivityAction.Argument>
<Sequence DisplayName="Compile and Test for Configuration" sap:VirtualizedContainerService.HintSize="1200,3900" mtbwt:BuildTrackingParticipant.Importance="Low">
<Sequence.Variables>
<Variable x:TypeArguments="x:String" Name="outputDirectory" />
<Variable x:TypeArguments="x:String" Name="logFileDropLocation" />
</Sequence.Variables>
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<Sequence DisplayName="Initialize Variables" sap:VirtualizedContainerService.HintSize="1178,387" mtbwt:BuildTrackingParticipant.Importance="Low">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<Assign x:TypeArguments="x:String" DisplayName="Initialize OutputDirectory" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Low" To="[outputDirectory]" Value="[If (platformConfiguration.IsEmpty Or BuildSettings.PlatformConfigurations.Count = 1, BinariesDirectory, If (platformConfiguration.IsPlatformEmptyOrAnyCpu, BinariesDirectory + &quot;\&quot; + platformConfiguration.Configuration, BinariesDirectory + &quot;\&quot; + platformConfiguration.Platform + &quot;\&quot; + platformConfiguration.Configuration))]" />
<If Condition="[Not String.IsNullOrEmpty(BuildDetail.DropLocation)]" DisplayName="If DropLocation is Set" sap:VirtualizedContainerService.HintSize="464,201" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Assign x:TypeArguments="x:String" DisplayName="Initialize LogFile Drop Location" sap:VirtualizedContainerService.HintSize="269,100" mtbwt:BuildTrackingParticipant.Importance="Low" To="[logFileDropLocation]" Value="[If (platformConfiguration.IsEmpty Or BuildSettings.PlatformConfigurations.Count = 1, BuildDetail.DropLocation + &quot;\logs&quot;, If (platformConfiguration.IsPlatformEmptyOrAnyCpu, BuildDetail.DropLocation + &quot;\logs\&quot; + platformConfiguration.Configuration, BuildDetail.DropLocation + &quot;\logs\&quot; + platformConfiguration.Platform + &quot;\&quot; + platformConfiguration.Configuration))]" />
</If.Then>
</If>
</Sequence>
<If Condition="[BuildSettings.HasProjectsToBuild]" DisplayName="If BuildSettings.HasProjectsToBuild" sap:VirtualizedContainerService.HintSize="1178,1379" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<ForEach x:TypeArguments="x:String" DisplayName="For Each Project in BuildSettings.ProjectsToBuild" sap:VirtualizedContainerService.HintSize="536,1278" mtbwt:BuildTrackingParticipant.Importance="Low" Values="[BuildSettings.ProjectsToBuild]">
<ActivityAction x:TypeArguments="x:String">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="x:String" Name="serverBuildProjectItem" />
</ActivityAction.Argument>
<TryCatch DisplayName="Try to Compile the Project" sap:VirtualizedContainerService.HintSize="506,1175" mtbwt:BuildTrackingParticipant.Importance="Low">
<TryCatch.Try>
<Sequence DisplayName="Compile the Project" sap:VirtualizedContainerService.HintSize="488,387" mtbwt:BuildTrackingParticipant.Importance="Low">
<Sequence.Variables>
<Variable x:TypeArguments="x:String" Name="localProject" />
</Sequence.Variables>
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtbwa:ConvertWorkspaceItem DisplayName="Convert Server Path to Local Path" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Low" Input="[serverBuildProjectItem]" Result="[localProject]" Workspace="[Workspace]" />
<If Condition="[Not System.IO.File.Exists(localProject)]" DisplayName="If Local File Doesn't Exist" sap:VirtualizedContainerService.HintSize="464,201">
<If.Then>
<Throw DisplayName="Throw FileNotFoundException" Exception="[New System.IO.FileNotFoundException(String.Format(&quot;The file {0} could not be found.&quot;, localProject), localProject)]" sap:VirtualizedContainerService.HintSize="219,100" />
</If.Then>
<If.Else>
<mtbwa:MSBuild CommandLineArguments="[String.Format(&quot;/p:SkipInvalidConfigurations=true {0}&quot;, MSBuildArguments)]" Configuration="[platformConfiguration.Configuration]" DisplayName="Run MSBuild for Project" GenerateVSPropsFile="[True]" sap:VirtualizedContainerService.HintSize="220,100" LogFileDropLocation="[logFileDropLocation]" OutDir="[outputDirectory]" Platform="[platformConfiguration.Platform]" Project="[localProject]" RunCodeAnalysis="[RunCodeAnalysis]" TargetsNotLogged="[New String() {&quot;GetNativeManifest&quot;, &quot;GetCopyToOutputDirectoryItems&quot;, &quot;GetTargetPath&quot;}]" ToolPlatform="[MSBuildPlatform]" Verbosity="[Verbosity]" />
</If.Else>
</If>
</Sequence>
</TryCatch.Try>
<TryCatch.Catches>
<Catch x:TypeArguments="s:Exception" sap:VirtualizedContainerService.HintSize="492,526">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">False</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<ActivityAction x:TypeArguments="s:Exception">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="s:Exception" Name="ex" />
</ActivityAction.Argument>
<Sequence DisplayName="Handle Exception" sap:VirtualizedContainerService.HintSize="486,495">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtbwa:SetBuildProperties CompilationStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Failed]" DisplayName="Set CompilationStatus to Failed" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Low" PropertiesToSet="CompilationStatus" />
<If Condition="[CreateWorkItem]" DisplayName="If CreateWorkItem" sap:VirtualizedContainerService.HintSize="464,247" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:InvokeForReason DisplayName="Create Work Item for non-Shelveset Builds" sap:VirtualizedContainerService.HintSize="281,146" Reason="Manual, IndividualCI, BatchedCI, Schedule, ScheduleForced, UserCreated">
<mtbwa:OpenWorkItem AssignedTo="[BuildDetail.RequestedFor]" Comment="[&quot;This work item was created by TFS Build on a build failure.&quot;]" CustomFields="[New Dictionary(Of String, String) From { {&quot;System.Reason&quot;, &quot;Build Failure&quot;}, {&quot;Microsoft.VSTS.TCM.ReproSteps&quot;, &quot;Start the build using TFS Build&quot;}, {&quot;Priority&quot;, &quot;1&quot;}, {&quot;Severity&quot;, &quot;1 - Critical&quot;} }]" DisplayName="Create Work Item" sap:VirtualizedContainerService.HintSize="200,22" Title="[String.Format(&quot;Build Failure in Build: {0}&quot;, BuildDetail.BuildNumber)]" Type="[&quot;Bug&quot;]" />
</mtbwa:InvokeForReason>
</If.Then>
</If>
<Rethrow DisplayName="Rethrow the exception so the build will stop" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Low" />
</Sequence>
</ActivityAction>
</Catch>
</TryCatch.Catches>
</TryCatch>
</ActivityAction>
</ForEach>
</If.Then>
</If>
<If Condition="[Not DisableTests]" DisplayName="If Not DisableTests" sap:VirtualizedContainerService.HintSize="1178,1930" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence DisplayName="Run Tests" sap:VirtualizedContainerService.HintSize="1053,1829" mtbwt:BuildTrackingParticipant.Importance="Low">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<If Condition="[Not TestSpecs Is Nothing]" DisplayName="If Not TestSpecs Is Nothing" sap:VirtualizedContainerService.HintSize="1031,1705" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<ForEach x:TypeArguments="mtbwa:TestSpec" DisplayName="For Each TestSpec in TestSpecs" sap:VirtualizedContainerService.HintSize="906,1604" mtbwt:BuildTrackingParticipant.Importance="Low" Values="[TestSpecs]">
<ActivityAction x:TypeArguments="mtbwa:TestSpec">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="mtbwa:TestSpec" Name="spec" />
</ActivityAction.Argument>
<TryCatch DisplayName="Try Run Tests" sap:VirtualizedContainerService.HintSize="876,1501" mtbwt:BuildTrackingParticipant.Importance="Low">
<TryCatch.Try>
<If Condition="[TypeOf spec Is Microsoft.TeamFoundation.Build.Workflow.Activities.TestMetadataFileSpec]" DisplayName="If spec Is TestMetadataFileSpec" sap:VirtualizedContainerService.HintSize="858,759" mtbwt:BuildTrackingParticipant.Importance="None">
<If.Then>
<Sequence DisplayName="Run MSTest for Metadata File" sap:VirtualizedContainerService.HintSize="222,658">
<Sequence.Variables>
<Variable x:TypeArguments="mtbwa:TestMetadataFileSpec" Name="testMetadataFile" />
<Variable x:TypeArguments="x:String" Name="localTestMetadata" />
</Sequence.Variables>
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<Assign x:TypeArguments="mtbwa:TestMetadataFileSpec" DisplayName="Assign spec to testMetadataFile" sap:VirtualizedContainerService.HintSize="200,22" mtbwt:BuildTrackingParticipant.Importance="Low" To="[testMetadataFile]" Value="[DirectCast(spec, Microsoft.TeamFoundation.Build.Workflow.Activities.TestMetadataFileSpec)]" />
<mtbwa:ConvertWorkspaceItem DisplayName="Convert Server Path to Local Path" sap:VirtualizedContainerService.HintSize="200,22" mtbwt:BuildTrackingParticipant.Importance="Low" Input="[testMetadataFile.MetadataFileName]" Result="[localTestMetadata]" Workspace="[Workspace]" />
<mtbwa:MSTest Category="[testMetadataFile.CategoryFilter]" CommandLineArguments="[testMetadataFile.MSTestCommandLineArgs]" DisplayName="Run MSTest for Metadata File" Flavor="[platformConfiguration.Configuration]" sap:VirtualizedContainerService.HintSize="200,22" MaxPriority="[testMetadataFile.MaximumPriority]" MinPriority="[testMetadataFile.MinimumPriority]" PathToResultsFilesRoot="[TestResultsDirectory]" Platform="[platformConfiguration.Platform]" SearchPathRoot="[outputDirectory]" TestLists="[testMetadataFile.TestLists]" TestMetadata="[localTestMetadata]" TestSettings="[String.Empty]" />
</Sequence>
</If.Then>
<If.Else>
<Sequence DisplayName="Run MSTest for Test Assemblies" sap:VirtualizedContainerService.HintSize="611,658" mtbwt:BuildTrackingParticipant.Importance="Low">
<Sequence.Variables>
<Variable x:TypeArguments="mtbwa:TestAssemblySpec" Name="testAssembly" />
<Variable x:TypeArguments="scg:IEnumerable(x:String)" Name="testAssemblies" />
<Variable x:TypeArguments="x:String" Default="[String.Empty]" Name="testFlavor" />
<Variable x:TypeArguments="x:String" Default="[String.Empty]" Name="testPlatform" />
</Sequence.Variables>
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<Assign x:TypeArguments="mtbwa:TestAssemblySpec" DisplayName="Assign spec to testAssembly" sap:VirtualizedContainerService.HintSize="589,22" mtbwt:BuildTrackingParticipant.Importance="Low" To="[testAssembly]" Value="[DirectCast(spec, Microsoft.TeamFoundation.Build.Workflow.Activities.TestAssemblySpec)]" />
<mtbwa:FindMatchingFiles DisplayName="Find Test Assemblies" sap:VirtualizedContainerService.HintSize="589,22" mtbwt:BuildTrackingParticipant.Importance="Low" MatchPattern="[String.Format(&quot;{0}\{1}&quot;, outputDirectory, testAssembly.AssemblyFileSpec)]" Result="[testAssemblies]" />
<If Condition="[testAssemblies.Count() &gt; 0]" DisplayName="If Test Assemblies Found" sap:VirtualizedContainerService.HintSize="589,410" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<If Condition="[testAssembly.HasTestSettingsFile]" DisplayName="If testAssembly.HasTestSettingsFile" sap:VirtualizedContainerService.HintSize="464,309" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence DisplayName="Find Test Settings File And Run MSTest" sap:VirtualizedContainerService.HintSize="231,208" mtbwt:BuildTrackingParticipant.Importance="Low">
<Sequence.Variables>
<Variable x:TypeArguments="x:String" Name="localTestSettings" />
</Sequence.Variables>
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtbwa:ConvertWorkspaceItem DisplayName="Convert Server Path to Local Path" sap:VirtualizedContainerService.HintSize="200,22" mtbwt:BuildTrackingParticipant.Importance="Low" Input="[testAssembly.TestSettingsFileName]" Result="[localTestSettings]" Workspace="[Workspace]" />
<mtbwa:MSTest Category="[testAssembly.CategoryFilter]" CommandLineArguments="[testAssembly.MSTestCommandLineArgs]" DisplayName="Run MSTest for Test Assemblies" Flavor="[platformConfiguration.Configuration]" sap:VirtualizedContainerService.HintSize="200,22" MaxPriority="[testAssembly.MaximumPriority]" MinPriority="[testAssembly.MinimumPriority]" PathToResultsFilesRoot="[TestResultsDirectory]" Platform="[platformConfiguration.Platform]" SearchPathRoot="[outputDirectory]" TestContainers="[testAssemblies]" TestSettings="[localTestSettings]" />
</Sequence>
</If.Then>
<If.Else>
<mtbwa:MSTest Category="[testAssembly.CategoryFilter]" CommandLineArguments="[testAssembly.MSTestCommandLineArgs]" DisplayName="Run MSTest for Test Assemblies" Flavor="[platformConfiguration.Configuration]" sap:VirtualizedContainerService.HintSize="208,208" MaxPriority="[testAssembly.MaximumPriority]" MinPriority="[testAssembly.MinimumPriority]" PathToResultsFilesRoot="[TestResultsDirectory]" Platform="[platformConfiguration.Platform]" SearchPathRoot="[outputDirectory]" TestContainers="[testAssemblies]" />
</If.Else>
</If>
</If.Then>
</If>
</Sequence>
</If.Else>
</If>
</TryCatch.Try>
<TryCatch.Catches>
<Catch x:TypeArguments="s:Exception" sap:VirtualizedContainerService.HintSize="862,480">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">False</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<ActivityAction x:TypeArguments="s:Exception">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="s:Exception" Name="testException" />
</ActivityAction.Argument>
<Sequence DisplayName="Handle MSTest Exception" sap:VirtualizedContainerService.HintSize="856,449">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<If Condition="[Not (TypeOf testException Is Microsoft.TeamFoundation.Build.Workflow.Activities.TestFailureException)]" DisplayName="If testException is NOT TestFailureException" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:WriteBuildError DisplayName="Write Test Failure Exception message" Message="[testException.Message]" />
</If.Then>
</If>
<mtbwa:SetBuildProperties DisplayName="Set TestStatus to Failed" sap:VirtualizedContainerService.HintSize="464,22" mtbwt:BuildTrackingParticipant.Importance="Low" PropertiesToSet="TestStatus" TestStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Failed]" />
<If Condition="[spec.FailBuildOnFailure]" DisplayName="If spec.FailBuildOnFailure" sap:VirtualizedContainerService.HintSize="464,201" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Assign x:TypeArguments="x:Boolean" DisplayName="Set treatTestFailureAsBuildFailure to True" sap:VirtualizedContainerService.HintSize="269,100" mtbwt:BuildTrackingParticipant.Importance="Low" To="[treatTestFailureAsBuildFailure]" Value="[True]" />
</If.Then>
</If>
</Sequence>
</ActivityAction>
</Catch>
</TryCatch.Catches>
</TryCatch>
</ActivityAction>
</ForEach>
</If.Then>
</If>
</Sequence>
</If.Then>
</If>
</Sequence>
</ActivityAction>
</ForEach>
<If Condition="[BuildDetail.CompilationStatus = Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Unknown]" DisplayName="If CompilationStatus = Unknown" sap:VirtualizedContainerService.HintSize="1230,201" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:SetBuildProperties CompilationStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Succeeded]" DisplayName="Set CompilationStatus to Succeeded" sap:VirtualizedContainerService.HintSize="269,100" mtbwt:BuildTrackingParticipant.Importance="Low" PropertiesToSet="CompilationStatus" />
</If.Then>
</If>
<If Condition="[BuildDetail.TestStatus = Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Unknown]" DisplayName="If TestStatus = Unknown" sap:VirtualizedContainerService.HintSize="1230,201" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:SetBuildProperties DisplayName="Set TestStatus to Succeeded" sap:VirtualizedContainerService.HintSize="269,100" mtbwt:BuildTrackingParticipant.Importance="Low" PropertiesToSet="TestStatus" TestStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Succeeded]" />
</If.Then>
</If>
<If Condition="[treatTestFailureAsBuildFailure And (BuildDetail.TestStatus = Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Failed)]" DisplayName="If TreatTestFailureAsBuildFailure And (TestStatus = Failed)" sap:VirtualizedContainerService.HintSize="1230,201" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:SetBuildProperties DisplayName="Set Status to Failed" sap:VirtualizedContainerService.HintSize="269,100" mtbwt:BuildTrackingParticipant.Importance="Low" PropertiesToSet="Status" Status="[Microsoft.TeamFoundation.Build.Client.BuildStatus.Failed]" />
</If.Then>
</If>
</Sequence>
</TryCatch.Try>
<TryCatch.Catches>
<Catch x:TypeArguments="s:Exception" sap:VirtualizedContainerService.HintSize="1256,106">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">False</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<ActivityAction x:TypeArguments="s:Exception">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="s:Exception" Name="compilationExceptionArgument" />
</ActivityAction.Argument>
<Assign x:TypeArguments="s:Exception" DisplayName="Save the Compilation Exception" sap:VirtualizedContainerService.HintSize="1250,75" mtbwt:BuildTrackingParticipant.Importance="None" To="[compilationException]" Value="[compilationExceptionArgument]" />
</ActivityAction>
</Catch>
</TryCatch.Catches>
</TryCatch>
<If Condition="[AssociateChangesetsAndWorkItems]" DisplayName="If AssociateChangesetsAndWorkItems" sap:VirtualizedContainerService.HintSize="464,5218" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:InvokeForReason DisplayName="Associate Changesets and Work Items for non-Shelveset Builds" sap:VirtualizedContainerService.HintSize="281,146" Reason="Manual, IndividualCI, BatchedCI, Schedule, ScheduleForced, UserCreated">
<mtbwa:AssociateChangesetsAndWorkItems DisplayName="Associate Changesets and Work Items" Result="[associatedChangesets]" />
</mtbwa:InvokeForReason>
</If.Then>
</If>
</Parallel>
<If Condition="[Not compilationException Is Nothing]" DisplayName="If a Compilation Exception Occurred" sap:VirtualizedContainerService.HintSize="1888,201" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Throw DisplayName="Rethrow Compilation Exception" Exception="[compilationException]" sap:VirtualizedContainerService.HintSize="269,100" mtbwt:BuildTrackingParticipant.Importance="Low" />
</If.Then>
</If>
<Parallel DisplayName="Get Impacted Tests, Index Sources and Publish Symbols" sap:VirtualizedContainerService.HintSize="1888,1557">
<If Condition="[PerformTestImpactAnalysis]" DisplayName="If PerformTestImpactAnalysis" sap:VirtualizedContainerService.HintSize="464,1511" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<Sequence DisplayName="Get Impacted Tests" sap:VirtualizedContainerService.HintSize="281,208" mtbwt:BuildTrackingParticipant.Importance="Low">
<Sequence.Variables>
<Variable x:TypeArguments="scg:IEnumerable(x:String)" Name="assemblies" />
</Sequence.Variables>
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtbwa:FindMatchingFiles DisplayName="Find Build Outputs" sap:VirtualizedContainerService.HintSize="200,22" mtbwt:BuildTrackingParticipant.Importance="Low" MatchPattern="[String.Format(&quot;{0}\**\*.dll;{0}\**\*.exe&quot;, BinariesDirectory)]" Result="[assemblies]" />
<mttbb:GetImpactedTests Assemblies="[assemblies]" AssociatedChangesets="[associatedChangesets]" BinariesRoot="[BinariesDirectory]" Build="[BuildDetail]" CodeChanges="{x:Null}" DisplayName="Get Impacted Tests" ImpactedTests="{x:Null}" Workspace="[Workspace]" />
</Sequence>
</If.Then>
</If>
<If Condition="[SourceAndSymbolServerSettings.IndexSources Or SourceAndSymbolServerSettings.HasSymbolStorePath]" DisplayName="If SourceAndSymbolServerSettings.IndexSources Or SourceAndSymbolServerSettings.HasSymbolStorePath" sap:VirtualizedContainerService.HintSize="690,1511" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<mtbwa:InvokeForReason DisplayName="Index Sources and Publish Symbols for Triggered Builds" sap:VirtualizedContainerService.HintSize="565,1410" Reason="Triggered">
<mtbwa:InvokeForReason.Variables>
<Variable x:TypeArguments="scg:IEnumerable(x:String)" Name="symbolFiles" />
</mtbwa:InvokeForReason.Variables>
<mtbwa:FindMatchingFiles DisplayName="Find Symbol Files" sap:VirtualizedContainerService.HintSize="543,22" mtbwt:BuildTrackingParticipant.Importance="Low" MatchPattern="[String.Format(&quot;{0}\**\*.pdb&quot;, BinariesDirectory)]" Result="[symbolFiles]" />
<If Condition="[SourceAndSymbolServerSettings.IndexSources]" DisplayName="If SourceAndSymbolServerSettings.IndexSources" sap:VirtualizedContainerService.HintSize="543,569" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<TryCatch DisplayName="Try Index Sources" sap:VirtualizedContainerService.HintSize="418,468" mtbwt:BuildTrackingParticipant.Importance="Low">
<TryCatch.Try>
<mtbwa:IndexSources DisplayName="Index Sources" FileList="[symbolFiles]" sap:VirtualizedContainerService.HintSize="400,100" />
</TryCatch.Try>
<TryCatch.Catches>
<Catch x:TypeArguments="s:Exception" sap:VirtualizedContainerService.HintSize="404,106">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">False</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<ActivityAction x:TypeArguments="s:Exception">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="s:Exception" Name="exception" />
</ActivityAction.Argument>
<mtbwa:WriteBuildError sap:VirtualizedContainerService.HintSize="398,75" Message="[exception.Message]" />
</ActivityAction>
</Catch>
</TryCatch.Catches>
</TryCatch>
</If.Then>
</If>
<If Condition="[SourceAndSymbolServerSettings.HasSymbolStorePath]" DisplayName="If SourceAndSymbolServerSettings.HasSymbolStorePath" sap:VirtualizedContainerService.HintSize="543,615" mtbwt:BuildTrackingParticipant.Importance="Low">
<If.Then>
<TryCatch DisplayName="Try Publish Symbols" sap:VirtualizedContainerService.HintSize="418,514" mtbwt:BuildTrackingParticipant.Importance="Low">
<TryCatch.Try>
<mtbwa:SharedResourceScope DisplayName="Synchronize Access to Symbol Store" sap:VirtualizedContainerService.HintSize="400,146" mtbwt:BuildTrackingParticipant.Importance="Low" MaxExecutionTime="[TimeSpan.Zero]" MaxWaitTime="[New TimeSpan(1, 0, 0)]" ResourceName="[SourceAndSymbolServerSettings.SymbolStorePath]">
<mtbwa:PublishSymbols DisplayName="Publish Symbols" FileList="[symbolFiles]" sap:VirtualizedContainerService.HintSize="200,22" ProductName="[BuildDetail.BuildDefinition.Name]" StorePath="[SourceAndSymbolServerSettings.SymbolStorePath]" Version="[BuildDetail.BuildNumber]" />
</mtbwa:SharedResourceScope>
</TryCatch.Try>
<TryCatch.Catches>
<Catch x:TypeArguments="s:Exception" sap:VirtualizedContainerService.HintSize="404,106">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">False</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<ActivityAction x:TypeArguments="s:Exception">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="s:Exception" Name="exception" />
</ActivityAction.Argument>
<mtbwa:WriteBuildError sap:VirtualizedContainerService.HintSize="398,75" Message="[exception.Message]" />
</ActivityAction>
</Catch>
</TryCatch.Catches>
</TryCatch>
</If.Then>
</If>
</mtbwa:InvokeForReason>
</If.Then>
</If>
</Parallel>
</Sequence>
</TryCatch.Try>
</TryCatch>
</mtbwa:AgentScope>
<mtbwa:InvokeForReason DisplayName="Check In Gated Changes for CheckInShelveset Builds" sap:VirtualizedContainerService.HintSize="1950,146" Reason="CheckInShelveset">
<mtbwa:CheckInGatedChanges DisplayName="Check In Gated Changes" sap:VirtualizedContainerService.HintSize="200,22" />
</mtbwa:InvokeForReason>
</Sequence>
</Activity>

+ 0
- 208
BuildProcessTemplates/LabDefaultTemplate.11.xaml View File

@@ -1,208 +0,0 @@
<Activity mc:Ignorable="sads sap" x:Class="TfsBuild.Process" this:Process.LabWorkflowParameters="[New Microsoft.TeamFoundation.Lab.Workflow.Activities.LabWorkflowDetails()]" this:Process.Verbosity="[Microsoft.TeamFoundation.Build.Workflow.BuildVerbosity.Normal]" this:Process.BuildNumberFormat="[&quot;$(BuildDefinitionName)_$(Date:yyyyMMdd)$(Rev:.r)&quot;]" this:Process.SupportedReasons="Manual, BatchedCI, Schedule, ScheduleForced" this:Process.TimeoutForDeploymentScriptInMinutes="30" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mt="clr-namespace:Microsoft.TeamFoundation;assembly=Microsoft.TeamFoundation.Common" xmlns:mtbc="clr-namespace:Microsoft.TeamFoundation.Build.Client;assembly=Microsoft.TeamFoundation.Build.Client" xmlns:mtbc1="clr-namespace:Microsoft.TeamFoundation.Build.Common;assembly=Microsoft.TeamFoundation.Build.Common" xmlns:mtbp="clr-namespace:Microsoft.TeamFoundation.Build.ProcessComponents;assembly=Microsoft.TeamFoundation.Build.ProcessComponents" xmlns:mtbw="clr-namespace:Microsoft.TeamFoundation.Build.Workflow;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtbwa="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Activities;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtbws="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Services;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtlc="clr-namespace:Microsoft.TeamFoundation.Lab.Client;assembly=Microsoft.TeamFoundation.Lab.Client" xmlns:mtltc="clr-namespace:Microsoft.TeamFoundation.Lab.TestIntegration.Client;assembly=Microsoft.TeamFoundation.Lab.TestIntegration.Client" xmlns:mtlwa="clr-namespace:Microsoft.TeamFoundation.Lab.Workflow.Activities;assembly=Microsoft.TeamFoundation.Lab.Workflow.Activities" xmlns:mtlwc="clr-namespace:Microsoft.TeamFoundation.Lab.WorkflowIntegration.Client;assembly=Microsoft.TeamFoundation.Lab.WorkflowIntegration.Client" xmlns:mttbb="clr-namespace:Microsoft.TeamFoundation.TestImpact.BuildIntegration.BuildActivities;assembly=Microsoft.TeamFoundation.TestImpact.BuildIntegration" xmlns:mttc="clr-namespace:Microsoft.TeamFoundation.TestManagement.Client;assembly=Microsoft.TeamFoundation.TestManagement.Client" xmlns:mtvc="clr-namespace:Microsoft.TeamFoundation.VersionControl.Client;assembly=Microsoft.TeamFoundation.VersionControl.Client" xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:s1="clr-namespace:System;assembly=System" xmlns:s2="clr-namespace:System;assembly=System.Core" xmlns:s3="clr-namespace:System;assembly=System.ServiceModel" xmlns:s4="clr-namespace:System;assembly=System.ComponentModel.Composition" xmlns:sa="clr-namespace:System.Activities;assembly=System.Activities" xmlns:sad="clr-namespace:System.Activities.Debugger;assembly=System.Activities" xmlns:sads="http://schemas.microsoft.com/netfx/2010/xaml/activities/debugger" xmlns:sap="http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib" xmlns:sl="clr-namespace:System.Linq;assembly=System.Core" xmlns:this="clr-namespace:TfsBuild" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<x:Members>
<x:Property Name="BuildProcessVersion" Type="x:String" />
<x:Property Name="Metadata" Type="mtbw:ProcessParameterMetadataCollection" />
<x:Property Name="LabWorkflowParameters" Type="InArgument(mtlwa:LabWorkflowDetails)" />
<x:Property Name="Verbosity" Type="InArgument(mtbw:BuildVerbosity)" />
<x:Property Name="BuildNumberFormat" Type="InArgument(x:String)" />
<x:Property Name="SupportedReasons" Type="mtbc:BuildReason" />
<x:Property Name="TimeoutForDeploymentScriptInMinutes" Type="InArgument(x:Int32)">
<x:Property.Attributes>
<RequiredArgumentAttribute />
</x:Property.Attributes>
</x:Property>
</x:Members>
<this:Process.BuildProcessVersion>11.0</this:Process.BuildProcessVersion>
<this:Process.Metadata>
<mtbw:ProcessParameterMetadataCollection>
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Category="Misc" DisplayName="Timeout For Each Deployment Script (in Minutes)" ParameterName="TimeoutForDeploymentScriptInMinutes" />
</mtbw:ProcessParameterMetadataCollection>
</this:Process.Metadata>
<sap:VirtualizedContainerService.HintSize>920,3702</sap:VirtualizedContainerService.HintSize>
<mva:VisualBasic.Settings>Assembly references and imported namespaces serialized as XML namespaces</mva:VisualBasic.Settings>
<Sequence DisplayName="Application Deployment Workflow" sad:XamlDebuggerXmlReader.FileName="D:\VSTLM\src\vset\LabManager\LabCustomActivities\Templates\LabDefaultTemplate.xaml" sap:VirtualizedContainerService.HintSize="880,3662" mva:VisualBasic.Settings="Assembly references and imported namespaces serialized as XML namespaces">
<Sequence.Variables>
<Variable x:TypeArguments="mtbc:IBuildDetail" Name="BuildDetail" />
<Variable x:TypeArguments="x:String" Name="LabEnvironmentUri" />
<Variable x:TypeArguments="x:String" Name="BuildLocation" />
<Variable x:TypeArguments="x:Int64" Name="SnapshotId" />
<Variable x:TypeArguments="x:Int32" Name="QueueBuildId" />
<Variable x:TypeArguments="mtbc:BuildStatus" Default="[Microsoft.TeamFoundation.Build.Client.BuildStatus.Succeeded]" Name="BuildStatus" />
<Variable x:TypeArguments="mtbc:IBuildDetail" Name="ChildBuildDetail" />
<Variable x:TypeArguments="mtbc:IBuildDetail" Name="SelectedBuildDetail" />
<Variable x:TypeArguments="x:String" Name="BuildNumber" />
<Variable x:TypeArguments="mtlc:LabEnvironment" Name="LabEnvironment" />
</Sequence.Variables>
<mtbwa:UpdateBuildNumber BuildNumberFormat="[BuildNumberFormat]" DisplayName="Update Build Number" sap:VirtualizedContainerService.HintSize="858,22" />
<mtbwa:GetBuildDetail DisplayName="Get Build Details" sap:VirtualizedContainerService.HintSize="858,22" Result="[BuildDetail]" />
<If Condition="[LabWorkflowParameters.BuildDetails.IsTeamSystemBuild = True AndAlso LabWorkflowParameters.BuildDetails.QueueNewBuild = True]" DisplayName="If Build is needed" sap:VirtualizedContainerService.HintSize="858,416">
<If.Then>
<Sequence DisplayName="Do Build" sap:VirtualizedContainerService.HintSize="301,308">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
<mtlwa:RunWorkflow BuildController="{x:Null}" LabEnvironmentUri="{x:Null}" BuildDefinition="[LabWorkflowParameters.BuildDetails.BuildDefinitionName]" DisplayName="Start Build Workflow" sap:VirtualizedContainerService.HintSize="242,22" ProjectName="[BuildDetail.TeamProject]" Result="[QueueBuildId]" />
<mtlwa:WaitForWorkflow AllowPartiallySucceededBuild="True" BuildDetails="[ChildBuildDetail]" DisplayName="Wait For Build To Complete" sap:VirtualizedContainerService.HintSize="242,22" LabWorkflowType="[Microsoft.TeamFoundation.Lab.Workflow.Activities.WorkflowType.Build]" MaxConsecutiveFailuresToIgnoreDuringWaitForCompletion="[3]" MaxWaitTime="[TimeSpan.Zero]" QueueBuildId="[QueueBuildId]" RefreshInterval="[System.TimeSpan.FromMinutes(1)]" Result="[BuildStatus]" ThrowOnError="True" />
<Assign DisplayName="Set Build Location" sap:VirtualizedContainerService.HintSize="242,60">
<Assign.To>
<OutArgument x:TypeArguments="x:Uri">[LabWorkflowParameters.BuildDetails.BuildUri]</OutArgument>
</Assign.To>
<Assign.Value>
<InArgument x:TypeArguments="x:Uri">[ChildBuildDetail.Uri]</InArgument>
</Assign.Value>
</Assign>
</Sequence>
</If.Then>
</If>
<mtlwa:WriteDeploymentInformation Url="{x:Null}" DeploymentInformationType="[Microsoft.TeamFoundation.Build.Common.DeploymentInformationTypes.Deploy]" DisplayName="Update Deployment Summary" sap:VirtualizedContainerService.HintSize="858,22" Message="[String.Format(&quot;Lab environment: {0}&quot;, LabWorkflowParameters.EnvironmentDetails.LabEnvironmentName)]" />
<mtlwa:GetBuildLocationAndBuildNumber BuildDetails="[LabWorkflowParameters.BuildDetails]" BuildNumber="[BuildNumber]" DisplayName="Get Build Location And Build Number" sap:VirtualizedContainerService.HintSize="858,22" Result="[BuildLocation]" SelectedBuild="[SelectedBuildDetail]" />
<If Condition="[LabWorkflowParameters.BuildDetails.IsTeamSystemBuild = True]" DisplayName="Compute build location needed" sap:VirtualizedContainerService.HintSize="858,208">
<If.Then>
<Assign DisplayName="Compute build path" sap:VirtualizedContainerService.HintSize="291,100">
<Assign.To>
<OutArgument x:TypeArguments="x:String">[BuildLocation]</OutArgument>
</Assign.To>
<Assign.Value>
<InArgument x:TypeArguments="x:String">[If(LabWorkflowParameters.BuildDetails.Configuration Is Nothing, BuildLocation, If(LabWorkflowParameters.BuildDetails.Configuration.IsEmpty Or (SelectedBuildDetail.Information.GetNodesByType(Microsoft.TeamFoundation.Build.Common.InformationTypes.ConfigurationSummary, True)).Count = 1, BuildLocation, If(LabWorkflowParameters.BuildDetails.Configuration.IsPlatformEmptyOrAnyCpu, BuildLocation + "\" + LabWorkflowParameters.BuildDetails.Configuration.Configuration, BuildLocation + "\" + LabWorkflowParameters.BuildDetails.Configuration.Platform + "\" + LabWorkflowParameters.BuildDetails.Configuration.Configuration)))]</InArgument>
</Assign.Value>
</Assign>
</If.Then>
</If>
<If Condition="[LabWorkflowParameters.EnvironmentDetails.Disposition = Microsoft.TeamFoundation.Lab.Client.LabEnvironmentDisposition.Stored]" DisplayName="If user selected stored environment" sap:VirtualizedContainerService.HintSize="858,208">
<If.Then>
<Throw DisplayName="Indicate error" Exception="[New System.Exception(&quot;You have selected an environment that is stored in the library. Select an environment that is deployed on a team project host group.&quot;)]" sap:VirtualizedContainerService.HintSize="269,100" />
</If.Then>
</If>
<Assign DisplayName="Get Lab Environment Uri" sap:VirtualizedContainerService.HintSize="858,22" >
<Assign.To>
<OutArgument x:TypeArguments="x:String">[LabEnvironmentUri]</OutArgument>
</Assign.To>
<Assign.Value>
<InArgument x:TypeArguments="x:String">[LabWorkflowParameters.EnvironmentDetails.LabEnvironmentUri.ToString()]</InArgument>
</Assign.Value>
</Assign>
<mtlwa:GetLabEnvironment DisplayName="Get Lab Environment" LabEnvironmentUri="[LabEnvironmentUri]" Result="[LabEnvironment]" />
<If Condition="[LabWorkflowParameters.EnvironmentDetails.RevertToSnapshot = True]" DisplayName=" If Restore Snapshot" sap:VirtualizedContainerService.HintSize="858,316">
<If.Then>
<Sequence DisplayName="Restore Snapshot" sap:VirtualizedContainerService.HintSize="231,208">
<mtlwa:GetLabEnvironmentSnapshotId DisplayName="Get Snapshot Details" sap:VirtualizedContainerService.HintSize="200,22" LabEnvironmentUri="[LabEnvironmentUri]" Result="[SnapshotId]" SnapshotName="[LabWorkflowParameters.EnvironmentDetails.SnapshotName]" />
<mtlwa:RestoreLabEnvironment DisplayName="Restore Lab Environment to Snapshot" sap:VirtualizedContainerService.HintSize="200,22" LabEnvironmentUri="[LabEnvironmentUri]" SnapshotId="[SnapshotId]" />
</Sequence>
</If.Then>
<If.Else>
<Sequence DisplayName="No Clean Snapshot" >
<If Condition="[Not String.Equals(Microsoft.TeamFoundation.Lab.Client.LabEnvironment.UnmanagedProvider, labEnvironment.LabProvider)]" DisplayName= "If Virtual Environment">
<If.Then>
<mtlwa:WriteDeploymentInformation Url="{x:Null}" DeploymentInformationType="[Microsoft.TeamFoundation.Build.Common.DeploymentInformationTypes.Deploy]" DisplayName="Clean snapshot not specified " sap:VirtualizedContainerService.HintSize="208,208" Message="Build definition did not specify a clean snapshot. It is a best practice to use clean snapshot when running the lab workflow." />
</If.Then>
</If>
</Sequence>
</If.Else>
</If>
<If Condition="[LabWorkflowParameters.DeploymentDetails.DeploymentNeeded = True or LabWorkflowParameters.TestParameters.RunTest = True]" DisplayName="If deployment or test needed" sap:VirtualizedContainerService.HintSize="858,1214">
<If.Then>
<mtlwa:WaitForEnvironmentReady DisplayName="Wait For Environment To Be Ready" sap:VirtualizedContainerService.HintSize="711,22" LabEnvironmentUri="[LabEnvironmentUri]" MaxWaitTime="[System.TimeSpan.FromMinutes(10)]" />
</If.Then>
</If>
<If Condition="[LabWorkflowParameters.DeploymentDetails.DeploymentNeeded = True]" DisplayName="If deployment needed" sap:VirtualizedContainerService.HintSize="858,1214">
<If.Then>
<Sequence DisplayName="Do deployment" sap:VirtualizedContainerService.HintSize="733,1106">
<mtlwa:ReserveEnvironmentForDeployment DisplayName="Reserve Environment For Deployment" sap:VirtualizedContainerService.HintSize="711,22" LabEnvironmentUri="[LabEnvironmentUri]" />
<TryCatch DisplayName="Deploy Build on Environment">
<TryCatch.Try>
<Sequence DisplayName="Deploying Build">
<ForEach x:TypeArguments="x:String" DisplayName="Run Deployment scripts" sap:VirtualizedContainerService.HintSize="711,254" Values="[LabWorkflowParameters.DeploymentDetails.Scripts]">
<ActivityAction x:TypeArguments="x:String">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="x:String" Name="deploymentConfigurationPair" />
</ActivityAction.Argument>
<mtlwa:RunDeploymentTask BuildLocation="[BuildLocation]" DeploymentScriptDetails="[deploymentConfigurationPair]" DisplayName="Run Deployment Task" sap:VirtualizedContainerService.HintSize="200,22" LabEnvironmentUri="[LabEnvironmentUri]" MaxWaitTime="[TimeSpan.FromMinutes(TimeoutForDeploymentScriptInMinutes)]" ThrowOnError="True" UseRoleForDeployment="[LabWorkflowParameters.DeploymentDetails.UseRoleForDeployment]" />
</ActivityAction>
</ForEach>
</Sequence>
</TryCatch.Try>
<TryCatch.Finally>
<mtlwa:ReleaseEnvironmentFromDeployment DisplayName="Release Environment From Deployment" sap:VirtualizedContainerService.HintSize="711,22" LabEnvironmentUri="[LabEnvironmentUri]" />
</TryCatch.Finally>
</TryCatch>
<mtlwa:WriteDeploymentInformation DeploymentInformationType="[Microsoft.TeamFoundation.Build.Common.DeploymentInformationTypes.Deploy]" DisplayName="Application Deployment Succeeded" sap:VirtualizedContainerService.HintSize="711,22" Message="[String.Format(&quot;The application was deployed successfully from the following build location:&quot;)]" Url="[BuildLocation]" />
<If Condition="[LabWorkflowParameters.DeploymentDetails.TakePostDeploymentSnapshot = True]" DisplayName="Post Deployment Snapshot" sap:VirtualizedContainerService.HintSize="711,626">
<If.Then>
<Sequence DisplayName="Take Post deployment Snapshot " sap:VirtualizedContainerService.HintSize="486,518">
<Sequence.Variables>
<Variable x:TypeArguments="x:Int64" Name="PostDeploymentSnapshotChainId" />
<Variable x:TypeArguments="x:String" Default="[String.Format(&quot;{0}_{1}&quot;, BuildDetail.BuildDefinition.Name, BuildDetail.BuildNumber)]" Name="PostDeploymentSnapshotName" />
</Sequence.Variables>
<If Condition="[String.IsNullOrEmpty(LabWorkflowParameters.DeploymentDetails.PostDeploymentSnapshotName) = False]" DisplayName="Check snapshot name" sap:VirtualizedContainerService.HintSize="464,208">
<If.Then>
<Assign sap:VirtualizedContainerService.HintSize="291,100">
<Assign.To>
<OutArgument x:TypeArguments="x:String">[PostDeploymentSnapshotName]</OutArgument>
</Assign.To>
<Assign.Value>
<InArgument x:TypeArguments="x:String">[If(LabWorkflowParameters.BuildDetails.IsTeamSystemBuild = True,String.Format("{0}_{1}_{2}", LabWorkflowParameters.DeploymentDetails.PostDeploymentSnapshotName, BuildNumber,BuildDetail.BuildNumber),String.Format("{0}_{1}", LabWorkflowParameters.DeploymentDetails.PostDeploymentSnapshotName, BuildDetail.BuildNumber))]</InArgument>
</Assign.Value>
</Assign>
</If.Then>
</If>
<mtlwa:SnapshotLabEnvironment DisplayName="Taking Post Deployment snapshot" sap:VirtualizedContainerService.HintSize="464,22" LabEnvironmentUri="[LabEnvironmentUri]" SnapshotChainId="[PostDeploymentSnapshotChainId]" SnapshotName="[PostDeploymentSnapshotName]" />
<mtlwa:WriteDeploymentInformation Url="{x:Null}" DeploymentInformationType="[Microsoft.TeamFoundation.Build.Common.DeploymentInformationTypes.Deploy]" DisplayName="Taking Snapshot succeeded" sap:VirtualizedContainerService.HintSize="464,22" Message="[String.Format(&quot;The following snapshot was taken after the deployment was finished: {0}&quot;, PostDeploymentSnapshotName)]" />
<mtlwa:WriteDeploymentInformation DeploymentInformationType="[Microsoft.TeamFoundation.Build.Common.DeploymentInformationTypes.ConnectToSnapshot]" DisplayName="Added connection link to the Snapshot" sap:VirtualizedContainerService.HintSize="464,22" Message="[PostDeploymentSnapshotName]" Url="[PostDeploymentSnapshotChainId.ToString()]" />
</Sequence>
</If.Then>
<If.Else>
<Sequence DisplayName = "No Post Deployment Snapshot">
<If Condition="[Not String.Equals(Microsoft.TeamFoundation.Lab.Client.LabEnvironment.UnmanagedProvider, labEnvironment.LabProvider)]" DisplayName= "If Virtual Environment">
<If.Then>
<mtlwa:WriteDeploymentInformation Url="{x:Null}" DeploymentInformationType="[Microsoft.TeamFoundation.Build.Common.DeploymentInformationTypes.Deploy]" DisplayName="Post deployment snapshot not specified" sap:VirtualizedContainerService.HintSize="200,518" Message="Build definition did not specify a post deployment snapshot. It is a best practice to take post deployment snapshot when running the lab workflow." />
</If.Then>
</If>
</Sequence>
</If.Else>
</If>
</Sequence>
</If.Then>
</If>
<If Condition="[LabWorkflowParameters.TestParameters.RunTest = True]" DisplayName="Run Tests on Environment" sap:VirtualizedContainerService.HintSize="858,604">
<If.Then>
<Sequence DisplayName="Run Tests" sap:VirtualizedContainerService.HintSize="656,498">
<Sequence.Variables>
<Variable x:TypeArguments="mtltc:TestingCapabilityInformation" Name="TestCapabilityInfo" />
<Variable x:TypeArguments="x:String" Name="variable1" />
<Variable x:TypeArguments="mtlwa:TestRunStatistics" Default="[New Microsoft.TeamFoundation.Lab.Workflow.Activities.TestRunStatistics()]" Name="TestResults" />
</Sequence.Variables>
<mtlwa:ExecuteRemoteTestRun2 MaxWaitTime="{x:Null}" TestEnvironment="{x:Null}" BuildNumber="[BuildNumber]" BuildDefinitionName="[LabWorkflowParameters.BuildDetails.BuildDefinitionName]" DisplayName="Running Tests" sap:VirtualizedContainerService.HintSize="634,22" LabEnvironmentUri="[LabEnvironmentUri]" MaxConsecutiveFailuresToIgnoreDuringWaitForCompletion="[3]" RefreshInterval="[System.TimeSpan.FromMinutes(1)]" Result="[TestResults]" TestDirectory="[BuildLocation]" TestParameters="[LabWorkflowParameters.TestParameters]" Title="[String.Format(&quot;{0}&quot;, BuildDetail.BuildNumber)]" />
<If Condition="[TestResults.PassedTests &lt;&gt; TestResults.TotalTests Or TestResults.TestRunStatus &lt;&gt; TestManagement.Client.TestRunState.Completed]" DisplayName="If all tests have not passed" sap:VirtualizedContainerService.HintSize="634,312">
<If.Then>
<If Condition="[(LabWorkflowParameters.BuildDetails.IsTeamSystemBuild = True AndAlso LabWorkflowParameters.BuildDetails.QueueNewBuild = True) Or (LabWorkflowParameters.DeploymentDetails.DeploymentNeeded = True)]" DisplayName="Set build status" sap:VirtualizedContainerService.HintSize="509,206">
<If.Then>
<Assign DisplayName="Partially succeeded" sap:VirtualizedContainerService.HintSize="242,100">
<Assign.To>
<OutArgument x:TypeArguments="mtbc:BuildStatus">[BuildStatus]</OutArgument>
</Assign.To>
<Assign.Value>
<InArgument x:TypeArguments="mtbc:BuildStatus">[Microsoft.TeamFoundation.Build.Client.BuildStatus.PartiallySucceeded]</InArgument>
</Assign.Value>
</Assign>
</If.Then>
<If.Else>
<Assign DisplayName="Failed" sap:VirtualizedContainerService.HintSize="242,100">
<Assign.To>
<OutArgument x:TypeArguments="mtbc:BuildStatus">[BuildStatus]</OutArgument>
</Assign.To>
<Assign.Value>
<InArgument x:TypeArguments="mtbc:BuildStatus">[Microsoft.TeamFoundation.Build.Client.BuildStatus.Failed]</InArgument>
</Assign.Value>
</Assign>
</If.Else>
</If>
</If.Then>
</If>
</Sequence>
</If.Then>
</If>
<mtbwa:SetBuildProperties DisplayName="Set build status" sap:VirtualizedContainerService.HintSize="858,22" PropertiesToSet="Status" Status="[BuildStatus]" />
</Sequence>
</Activity>

+ 0
- 76
BuildProcessTemplates/UpgradeTemplate.xaml View File

@@ -1,76 +0,0 @@
<Activity mc:Ignorable="sad" x:Class="TfsBuild.Process" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mtbc="clr-namespace:Microsoft.TeamFoundation.Build.Client;assembly=Microsoft.TeamFoundation.Build.Client" xmlns:mtbw="clr-namespace:Microsoft.TeamFoundation.Build.Workflow;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtbwa="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Activities;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtbwt="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Tracking;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtvc="clr-namespace:Microsoft.TeamFoundation.VersionControl.Client;assembly=Microsoft.TeamFoundation.VersionControl.Client" xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:sad="http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation" xmlns:sad1="clr-namespace:System.Activities.Debugger;assembly=System.Activities" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib" xmlns:this="clr-namespace:TfsBuild;" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<x:Members>
<x:Property Name="ConfigurationFolderPath" Type="InArgument(x:String)" />
<x:Property Name="AgentSettings" Type="InArgument(mtbwa:AgentSettings)" />
<x:Property Name="MSBuildArguments" Type="InArgument(x:String)" />
<x:Property Name="MSBuildPlatform" Type="InArgument(mtbwa:ToolPlatform)" />
<x:Property Name="DoNotDownloadBuildType" Type="InArgument(x:Boolean)" />
<x:Property Name="LogFilePerProject" Type="InArgument(x:Boolean)" />
<x:Property Name="SourcesSubdirectory" Type="InArgument(x:String)" />
<x:Property Name="BinariesSubdirectory" Type="InArgument(x:String)" />
<x:Property Name="TestResultsSubdirectory" Type="InArgument(x:String)" />
<x:Property Name="RecursionType" Type="InArgument(mtvc:RecursionType)" />
<x:Property Name="Verbosity" Type="InArgument(mtbw:BuildVerbosity)" />
<x:Property Name="Metadata" Type="mtbw:ProcessParameterMetadataCollection" />
<x:Property Name="SupportedReasons" Type="mtbc:BuildReason" />
</x:Members>
<this:Process.ConfigurationFolderPath>
<InArgument x:TypeArguments="x:String" />
</this:Process.ConfigurationFolderPath>
<this:Process.AgentSettings>[New Microsoft.TeamFoundation.Build.Workflow.Activities.AgentSettings() With {.MaxWaitTime = New System.TimeSpan(4, 0, 0), .MaxExecutionTime = New System.TimeSpan(0, 0, 0), .TagComparison = Microsoft.TeamFoundation.Build.Workflow.Activities.TagComparison.MatchExactly }]</this:Process.AgentSettings>
<this:Process.MSBuildArguments>
<InArgument x:TypeArguments="x:String" />
</this:Process.MSBuildArguments>
<this:Process.MSBuildPlatform>[Microsoft.TeamFoundation.Build.Workflow.Activities.ToolPlatform.Auto]</this:Process.MSBuildPlatform>
<this:Process.DoNotDownloadBuildType>[False]</this:Process.DoNotDownloadBuildType>
<this:Process.LogFilePerProject>[False]</this:Process.LogFilePerProject>
<this:Process.SourcesSubdirectory>
<InArgument x:TypeArguments="x:String" />
</this:Process.SourcesSubdirectory>
<this:Process.BinariesSubdirectory>
<InArgument x:TypeArguments="x:String" />
</this:Process.BinariesSubdirectory>
<this:Process.TestResultsSubdirectory>
<InArgument x:TypeArguments="x:String" />
</this:Process.TestResultsSubdirectory>
<this:Process.RecursionType>[Microsoft.TeamFoundation.VersionControl.Client.RecursionType.OneLevel]</this:Process.RecursionType>
<this:Process.Verbosity>[Microsoft.TeamFoundation.Build.Workflow.BuildVerbosity.Normal]</this:Process.Verbosity>
<this:Process.Metadata>
<mtbw:ProcessParameterMetadataCollection />
</this:Process.Metadata>
<this:Process.SupportedReasons>All</this:Process.SupportedReasons>
<mva:VisualBasic.Settings>Assembly references and imported namespaces serialized as XML namespaces</mva:VisualBasic.Settings>
<Sequence mtbwt:BuildTrackingParticipant.Importance="None">
<Sequence.Variables>
<Variable x:TypeArguments="mtbc:IBuildDetail" Name="BuildDetail" />
</Sequence.Variables>
<mtbwa:GetBuildDetail DisplayName="Get the Build" Result="[BuildDetail]" />
<mtbwa:InvokeForReason DisplayName="Update Build Number for Triggered Builds" Reason="Triggered">
<mtbwa:UpdateBuildNumber BuildNumberFormat="[&quot;$(BuildDefinitionName)_$(Date:yyyyMMdd)$(Rev:.r)&quot;]" DisplayName="Update Build Number" />
</mtbwa:InvokeForReason>
<mtbwa:AgentScope DisplayName="Run On Agent" MaxExecutionTime="[AgentSettings.MaxExecutionTime]" MaxWaitTime="[AgentSettings.MaxWaitTime]" ReservationSpec="[AgentSettings.GetAgentReservationSpec()]">
<mtbwa:AgentScope.Variables>
<Variable x:TypeArguments="x:String" Name="buildDirectory" />
</mtbwa:AgentScope.Variables>
<mtbwa:GetBuildDirectory DisplayName="Get the Build Directory" Result="[buildDirectory]" />
<If Condition="[Not String.IsNullOrEmpty(ConfigurationFolderPath)]" DisplayName="If Not String.IsNullOrEmpty(ConfigurationFolderPath)">
<If.Then>
<mtbwa:TfsBuild BinariesSubdirectory="[BinariesSubdirectory]" BuildDirectory="[buildDirectory]" CommandLineArguments="[MSBuildArguments]" ConfigurationFolderPath="[ConfigurationFolderPath]" DisplayName="Run TfsBuild for Configuration Folder" DoNotDownloadBuildType="[DoNotDownloadBuildType]" LogFilePerProject="[LogFilePerProject]" RecursionType="[RecursionType]" SourcesSubdirectory="[SourcesSubdirectory]" TestResultsSubdirectory="[TestResultsSubdirectory]" ToolPlatform="[MSBuildPlatform]" Verbosity="[Verbosity]" />
</If.Then>
</If>
<If Condition="[BuildDetail.CompilationStatus = Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Unknown]" DisplayName="If CompilationStatus = Unknown">
<If.Then>
<mtbwa:SetBuildProperties CompilationStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Succeeded]" DisplayName="Set CompilationStatus to Succeeded" PropertiesToSet="CompilationStatus" />
</If.Then>
</If>
<If Condition="[BuildDetail.TestStatus = Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Unknown]" DisplayName="If TestStatus = Unknown">
<If.Then>
<mtbwa:SetBuildProperties DisplayName="Set TestStatus to Succeeded" PropertiesToSet="TestStatus" TestStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Succeeded]" />
</If.Then>
</If>
</mtbwa:AgentScope>
<mtbwa:InvokeForReason Reason="CheckInShelveset">
<mtbwa:CheckInGatedChanges DisplayName="Check In Gated Changes" />
</mtbwa:InvokeForReason>
</Sequence>
</Activity>

+ 0
- 33
DocX.Xamarin.sln View File

@@ -1,33 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DocX.iOS.Test", "DocX.iOS.Test\DocX.iOS.Test.csproj", "{E504B3DA-ED72-4A45-ADCC-F573908A84EB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DocX.iOS", "DocX.iOS\DocX.iOS.csproj", "{70FC6AB5-5C6C-4E7A-92B7-0B24E16FE0EC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|iPhoneSimulator = Debug|iPhoneSimulator
Release|iPhone = Release|iPhone
Release|iPhoneSimulator = Release|iPhoneSimulator
Debug|iPhone = Debug|iPhone
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{70FC6AB5-5C6C-4E7A-92B7-0B24E16FE0EC}.Debug|iPhone.ActiveCfg = Debug|Any CPU
{70FC6AB5-5C6C-4E7A-92B7-0B24E16FE0EC}.Debug|iPhone.Build.0 = Debug|Any CPU
{70FC6AB5-5C6C-4E7A-92B7-0B24E16FE0EC}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU
{70FC6AB5-5C6C-4E7A-92B7-0B24E16FE0EC}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU
{70FC6AB5-5C6C-4E7A-92B7-0B24E16FE0EC}.Release|iPhone.ActiveCfg = Release|Any CPU
{70FC6AB5-5C6C-4E7A-92B7-0B24E16FE0EC}.Release|iPhone.Build.0 = Release|Any CPU
{70FC6AB5-5C6C-4E7A-92B7-0B24E16FE0EC}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU
{70FC6AB5-5C6C-4E7A-92B7-0B24E16FE0EC}.Release|iPhoneSimulator.Build.0 = Release|Any CPU
{E504B3DA-ED72-4A45-ADCC-F573908A84EB}.Debug|iPhone.ActiveCfg = Debug|iPhone
{E504B3DA-ED72-4A45-ADCC-F573908A84EB}.Debug|iPhone.Build.0 = Debug|iPhone
{E504B3DA-ED72-4A45-ADCC-F573908A84EB}.Debug|iPhoneSimulator.ActiveCfg = Debug|iPhoneSimulator
{E504B3DA-ED72-4A45-ADCC-F573908A84EB}.Debug|iPhoneSimulator.Build.0 = Debug|iPhoneSimulator
{E504B3DA-ED72-4A45-ADCC-F573908A84EB}.Release|iPhone.ActiveCfg = Release|iPhone
{E504B3DA-ED72-4A45-ADCC-F573908A84EB}.Release|iPhone.Build.0 = Release|iPhone
{E504B3DA-ED72-4A45-ADCC-F573908A84EB}.Release|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator
{E504B3DA-ED72-4A45-ADCC-F573908A84EB}.Release|iPhoneSimulator.Build.0 = Release|iPhoneSimulator
EndGlobalSection
EndGlobal

+ 0
- 4459
DocX.cs
File diff suppressed because it is too large
View File


+ 0
- 107
DocX.iOS.Test/DocX.iOS.Test.csproj View File

@@ -1,107 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">iPhoneSimulator</Platform>
<ProjectTypeGuids>{FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ProjectGuid>{E504B3DA-ED72-4A45-ADCC-F573908A84EB}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>DocX.iOS.Test</RootNamespace>
<IPhoneResourcePrefix>Resources</IPhoneResourcePrefix>
<AssemblyName>DocX.iOS.Test</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhoneSimulator' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\iPhoneSimulator\Debug</OutputPath>
<DefineConstants>DEBUG;ENABLE_TEST_CLOUD;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
<MtouchArch>i386</MtouchArch>
<MtouchLink>None</MtouchLink>
<MtouchUseRefCounting>true</MtouchUseRefCounting>
<MtouchUseSGen>true</MtouchUseSGen>
<MtouchFastDev>true</MtouchFastDev>
<MtouchDebug>true</MtouchDebug>
<CodesignKey>iPhone Developer</CodesignKey>
<MtouchProfiling>true</MtouchProfiling>
<MtouchI18n>west</MtouchI18n>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhone' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\iPhone\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
<MtouchArch>ARMv7, ARM64</MtouchArch>
<CodesignEntitlements>Entitlements.plist</CodesignEntitlements>
<MtouchFloat32>true</MtouchFloat32>
<MtouchUseSGen>true</MtouchUseSGen>
<CodesignKey>iPhone Developer</CodesignKey>
<MtouchUseRefCounting>true</MtouchUseRefCounting>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhoneSimulator' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\iPhoneSimulator\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
<MtouchArch>i386</MtouchArch>
<MtouchLink>None</MtouchLink>
<MtouchUseRefCounting>true</MtouchUseRefCounting>
<CodesignKey>iPhone Developer</CodesignKey>
<MtouchUseSGen>true</MtouchUseSGen>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhone' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\iPhone\Debug</OutputPath>
<DefineConstants>DEBUG;ENABLE_TEST_CLOUD;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
<MtouchArch>ARMv7, ARM64</MtouchArch>
<CodesignEntitlements>Entitlements.plist</CodesignEntitlements>
<MtouchFloat32>true</MtouchFloat32>
<CodesignKey>iPhone Developer</CodesignKey>
<DeviceSpecificBuild>true</DeviceSpecificBuild>
<MtouchDebug>true</MtouchDebug>
<MtouchUseSGen>true</MtouchUseSGen>
<MtouchUseRefCounting>true</MtouchUseRefCounting>
<MtouchProfiling>true</MtouchProfiling>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
<Reference Include="Xamarin.iOS" />
</ItemGroup>
<ItemGroup>
<ImageAsset Include="Resources\Images.xcassets\AppIcons.appiconset\Contents.json" />
</ItemGroup>
<ItemGroup>
<InterfaceDefinition Include="Resources\LaunchScreen.xib" />
</ItemGroup>
<ItemGroup>
<None Include="Info.plist" />
<None Include="Entitlements.plist" />
</ItemGroup>
<ItemGroup>
<Compile Include="Sources\App.cs" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\iOS\Xamarin.iOS.CSharp.targets" />
<ItemGroup>
<ProjectReference Include="..\DocX.iOS\DocX.iOS.csproj">
<Project>{70FC6AB5-5C6C-4E7A-92B7-0B24E16FE0EC}</Project>
<Name>DocX.iOS</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Folder Include="Sources\" />
</ItemGroup>
</Project>

+ 0
- 6
DocX.iOS.Test/Entitlements.plist View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
</dict>
</plist>

+ 0
- 43
DocX.iOS.Test/Info.plist View File

@@ -1,43 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key>
<string>DocX Test</string>
<key>CFBundleIdentifier</key>
<string>com.managingsoftware.docx.docx-ios-test</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>MinimumOSVersion</key>
<string>9.3</string>
<key>UIDeviceFamily</key>
<array>
<integer>1</integer>
<integer>2</integer>
</array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>XSAppIconAssets</key>
<string>Resources/Images.xcassets/AppIcons.appiconset</string>
</dict>
</plist>

+ 0
- 162
DocX.iOS.Test/Resources/Images.xcassets/AppIcons.appiconset/Contents.json View File

@@ -1,162 +0,0 @@
{
"images": [
{
"idiom": "iphone",
"size": "29x29",
"scale": "1x"
},
{
"idiom": "iphone",
"size": "29x29",
"scale": "2x"
},
{
"idiom": "iphone",
"size": "29x29",
"scale": "3x"
},
{
"idiom": "iphone",
"size": "40x40",
"scale": "2x"
},
{
"idiom": "iphone",
"size": "40x40",
"scale": "3x"
},
{
"idiom": "iphone",
"size": "57x57",
"scale": "1x"
},
{
"idiom": "iphone",
"size": "57x57",
"scale": "2x"
},
{
"idiom": "iphone",
"size": "60x60",
"scale": "2x"
},
{
"idiom": "iphone",
"size": "60x60",
"scale": "3x"
},
{
"idiom": "ipad",
"size": "29x29",
"scale": "1x"
},
{
"idiom": "ipad",
"size": "29x29",
"scale": "2x"
},
{
"idiom": "ipad",
"size": "40x40",
"scale": "1x"
},
{
"idiom": "ipad",
"size": "40x40",
"scale": "2x"
},
{
"idiom": "ipad",
"size": "50x50",
"scale": "1x"
},
{
"idiom": "ipad",
"size": "50x50",
"scale": "2x"
},
{
"idiom": "ipad",
"size": "72x72",
"scale": "1x"
},
{
"idiom": "ipad",
"size": "72x72",
"scale": "2x"
},
{
"idiom": "ipad",
"size": "76x76",
"scale": "1x"
},
{
"idiom": "ipad",
"size": "76x76",
"scale": "2x"
},
{
"idiom": "car",
"size": "120x120",
"scale": "1x"
},
{
"size": "24x24",
"idiom": "watch",
"scale": "2x",
"role": "notificationCenter",
"subtype": "38mm"
},
{
"size": "27.5x27.5",
"idiom": "watch",
"scale": "2x",
"role": "notificationCenter",
"subtype": "42mm"
},
{
"size": "29x29",
"idiom": "watch",
"role": "companionSettings",
"scale": "2x"
},
{
"size": "29x29",
"idiom": "watch",
"role": "companionSettings",
"scale": "3x"
},
{
"size": "40x40",
"idiom": "watch",
"scale": "2x",
"role": "appLauncher",
"subtype": "38mm"
},
{
"size": "44x44",
"idiom": "watch",
"scale": "2x",
"role": "longLook",
"subtype": "42mm"
},
{
"size": "86x86",
"idiom": "watch",
"scale": "2x",
"role": "quickLook",
"subtype": "38mm"
},
{
"size": "98x98",
"idiom": "watch",
"scale": "2x",
"role": "quickLook",
"subtype": "42mm"
}
],
"info": {
"version": 1,
"author": "xcode"
}
}

+ 0
- 32
DocX.iOS.Test/Resources/LaunchScreen.xib View File

@@ -1,32 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="6214" systemVersion="14A314h" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6207"/>
<capability name="Constraints with non-1.0 multipliers" minToolsVersion="5.1"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="iN0-l3-epB">
<rect key="frame" x="0.0" y="0.0" width="480" height="480"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="DocX Test" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="kId-c2-rCX" misplaced="YES">
<rect key="frame" x="20" y="140" width="441" height="43"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="kId-c2-rCX" firstAttribute="centerY" secondItem="iN0-l3-epB" secondAttribute="bottom" multiplier="1/3" constant="1" id="5cJ-9S-tgC"/>
<constraint firstAttribute="centerX" secondItem="kId-c2-rCX" secondAttribute="centerX" id="Koa-jz-hwk"/>
<constraint firstItem="kId-c2-rCX" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" constant="20" symbolic="YES" id="fvb-Df-36g"/>
</constraints>
<nil key="simulatedStatusBarMetrics"/>
<freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
<point key="canvasLocation" x="548" y="455"/>
</view>
</objects>
</document>

+ 0
- 143
DocX.iOS.Test/Sources/App.cs View File

@@ -1,143 +0,0 @@
using System;
using System.IO;

using Foundation;
using UIKit;

namespace DocX.iOS.Test
{
[Register ("App")]

public class App : UIApplicationDelegate
{
// Main

private static void Main (string[] args)
{
UIApplication.Main (args, null, "App");
}

// constants

private const string messageFormat = @"
<html>
<head>
<style type='text/css'>

html, body
{{
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
font-family: Arial;
vertical-align: baseline;
color: #666666;
}}

body
{{
padding: 2em 2em;
}}

pre
{{
white-space: pre-wrap;
}}

</style>
</head>
<body>
<h2>{0}</h2>
<pre><code>{1}</code></pre>
</body>
</html>
";
// publics

public override UIWindow Window { get; set; }

// FinishedLaunching

public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
// create webview + controller

var controller = new UIViewController ();

controller.Title = "DocX - Test";

var webview = new UIWebView (controller.View.Frame);

webview.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
webview.ScalesPageToFit = true;

controller.View.AddSubview (webview);

// create navigation controller

var navigation = new UINavigationController (controller);

// initialize window

this.Window = new UIWindow (UIScreen.MainScreen.Bounds);

this.Window.RootViewController = navigation;

this.Window.MakeKeyAndVisible ();

//

try
{
// path to our temp docx file

string pathDocx = Path.Combine(Path.GetTempPath (), "Document.docx");

// inform user of what we are about to do

webview.LoadHtmlString (string.Format(messageFormat, "Generating .docx file, please wait...", pathDocx), null);

// generating docx

using (var document = Novacode.DocX.Create (pathDocx))
{
Novacode.Paragraph p = document.InsertParagraph();

p.Append("This is a Word Document");

p = document.InsertParagraph();

p.Append("");

p = document.InsertParagraph();

p.Append("Hello World");

document.Save();
}

// showing docx in webview, with delay, otherwise we don't see our initial message

this.Invoke(() => {

webview.LoadRequest (NSUrlRequest.FromUrl (NSUrl.FromFilename (pathDocx)));

}, 2.0f);

// done
}
catch (Exception e)
{
webview.LoadHtmlString (string.Format(messageFormat, "Exception Occurred :", e), null);
}

// done

return true;
}
}
}

+ 0
- 200
DocX.iOS/DocX.iOS.csproj View File

@@ -1,200 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectTypeGuids>{FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ProjectGuid>{70FC6AB5-5C6C-4E7A-92B7-0B24E16FE0EC}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>DocX.iOS</RootNamespace>
<IPhoneResourcePrefix>Resources</IPhoneResourcePrefix>
<AssemblyName>DocX.iOS</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
<NoWarn>219;414;168;</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
<NoWarn>219;414;168;</NoWarn>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
<Reference Include="Xamarin.iOS" />
<Reference Include="System.Xml.Linq" />
<Reference Include="OpenTK-1.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Resources\" />
<Folder Include="Sources\" />
<Folder Include="Sources\Charts\" />
<Folder Include="System\" />
<Folder Include="System\IO\" />
<Folder Include="System\IO\Packaging\" />
<Folder Include="System\Drawing\" />
<Folder Include="Zip\" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="..\DocX\Charts\Axis.cs">
<Link>Sources\Charts\Axis.cs</Link>
</Compile>
<Compile Include="..\DocX\Charts\BarChart.cs">
<Link>Sources\Charts\BarChart.cs</Link>
</Compile>
<Compile Include="..\DocX\Charts\Chart.cs">
<Link>Sources\Charts\Chart.cs</Link>
</Compile>
<Compile Include="..\DocX\Charts\LineChart.cs">
<Link>Sources\Charts\LineChart.cs</Link>
</Compile>
<Compile Include="..\DocX\Charts\PieChart.cs">
<Link>Sources\Charts\PieChart.cs</Link>
</Compile>
<Compile Include="..\DocX\Charts\XElementHelpers.cs">
<Link>Sources\Charts\XElementHelpers.cs</Link>
</Compile>
<Compile Include="..\DocX\Bookmark.cs">
<Link>Sources\Bookmark.cs</Link>
</Compile>
<Compile Include="..\DocX\BookmarkCollection.cs">
<Link>Sources\BookmarkCollection.cs</Link>
</Compile>
<Compile Include="..\DocX\Border.cs">
<Link>Sources\Border.cs</Link>
</Compile>
<Compile Include="..\DocX\Container.cs">
<Link>Sources\Container.cs</Link>
</Compile>
<Compile Include="..\DocX\CustomProperty.cs">
<Link>Sources\CustomProperty.cs</Link>
</Compile>
<Compile Include="..\DocX\DocProperty.cs">
<Link>Sources\DocProperty.cs</Link>
</Compile>
<Compile Include="..\DocX\DocX.cs">
<Link>Sources\DocX.cs</Link>
</Compile>
<Compile Include="..\DocX\DocumentTypes.cs">
<Link>Sources\DocumentTypes.cs</Link>
</Compile>
<Compile Include="..\DocX\ExtensionsHeadings.cs">
<Link>Sources\ExtensionsHeadings.cs</Link>
</Compile>
<Compile Include="..\DocX\Footer.cs">
<Link>Sources\Footer.cs</Link>
</Compile>
<Compile Include="..\DocX\Footers.cs">
<Link>Sources\Footers.cs</Link>
</Compile>
<Compile Include="..\DocX\FormattedText.cs">
<Link>Sources\FormattedText.cs</Link>
</Compile>
<Compile Include="..\DocX\Formatting.cs">
<Link>Sources\Formatting.cs</Link>
</Compile>
<Compile Include="..\DocX\Header.cs">
<Link>Sources\Header.cs</Link>
</Compile>
<Compile Include="..\DocX\Headers.cs">
<Link>Sources\Headers.cs</Link>
</Compile>
<Compile Include="..\DocX\HelperFunctions.cs">
<Link>Sources\HelperFunctions.cs</Link>
</Compile>
<Compile Include="..\DocX\Hyperlink.cs">
<Link>Sources\Hyperlink.cs</Link>
</Compile>
<Compile Include="..\DocX\IParagraphContainer.cs">
<Link>Sources\IParagraphContainer.cs</Link>
</Compile>
<Compile Include="..\DocX\Image.cs">
<Link>Sources\Image.cs</Link>
</Compile>
<Compile Include="..\DocX\List.cs">
<Link>Sources\List.cs</Link>
</Compile>
<Compile Include="..\DocX\PageLayout.cs">
<Link>Sources\PageLayout.cs</Link>
</Compile>
<Compile Include="..\DocX\Paragraph.cs">
<Link>Sources\Paragraph.cs</Link>
</Compile>
<Compile Include="..\DocX\Picture.cs">
<Link>Sources\Picture.cs</Link>
</Compile>
<Compile Include="..\DocX\Section.cs">
<Link>Sources\Section.cs</Link>
</Compile>
<Compile Include="..\DocX\Table.cs">
<Link>Sources\Table.cs</Link>
</Compile>
<Compile Include="..\DocX\TableOfContents.cs">
<Link>Sources\TableOfContents.cs</Link>
</Compile>
<Compile Include="..\DocX\_BaseClasses.cs">
<Link>Sources\_BaseClasses.cs</Link>
</Compile>
<Compile Include="..\DocX\_Enumerations.cs">
<Link>Sources\_Enumerations.cs</Link>
</Compile>
<Compile Include="..\DocX\_Extensions.cs">
<Link>Sources\_Extensions.cs</Link>
</Compile>
<Compile Include="System\IO\Packaging\Check.cs" />
<Compile Include="System\IO\Packaging\CompressionOption.cs" />
<Compile Include="System\IO\Packaging\Package.cs" />
<Compile Include="System\IO\Packaging\PackagePart.cs" />
<Compile Include="System\IO\Packaging\PackagePartCollection.cs" />
<Compile Include="System\IO\Packaging\PackageProperties.cs" />
<Compile Include="System\IO\Packaging\PackagePropertiesPart.cs" />
<Compile Include="System\IO\Packaging\PackageRelationship.cs" />
<Compile Include="System\IO\Packaging\PackageRelationshipCollection.cs" />
<Compile Include="System\IO\Packaging\PackUriHelper.cs" />
<Compile Include="System\IO\Packaging\PackUriParser.cs" />
<Compile Include="System\IO\Packaging\TargetMode.cs" />
<Compile Include="System\IO\Packaging\ZipPackage.cs" />
<Compile Include="System\IO\Packaging\ZipPackagePart.cs" />
<Compile Include="System\IO\Packaging\ZipPartStream.cs" />
<Compile Include="System\Drawing\ColorTranslator.cs" />
<Compile Include="System\Drawing\FontFamily.cs" />
<Compile Include="System\Drawing\Image.cs" />
<Compile Include="Zip\ZipStorer.cs" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\iOS\Xamarin.iOS.CSharp.targets" />
<ItemGroup>
<EmbeddedResource Include="..\DocX\Resources\default_styles.xml.gz">
<Link>Resources\default_styles.xml.gz</Link>
<LogicalName>Novacode.Resources.default_styles.xml.gz</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="..\DocX\Resources\numbering.default_bullet_abstract.xml.gz">
<Link>Resources\numbering.default_bullet_abstract.xml.gz</Link>
<LogicalName>Novacode.Resources.default_bullet_abstract.xml.gz</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="..\DocX\Resources\numbering.default_decimal_abstract.xml.gz">
<Link>Resources\numbering.default_decimal_abstract.xml.gz</Link>
<LogicalName>Novacode.Resources.default_decimal_abstract.xml.gz</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="..\DocX\Resources\numbering.xml.gz">
<Link>Resources\numbering.xml.gz</Link>
<LogicalName>Novacode.Resources.numbering.xml.gz</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="..\DocX\Resources\styles.xml.gz">
<Link>Resources\styles.xml.gz</Link>
<LogicalName>Novacode.Resources.styles.xml.gz</LogicalName>
</EmbeddedResource>
</ItemGroup>
</Project>

+ 0
- 27
DocX.iOS/Properties/AssemblyInfo.cs View File

@@ -1,27 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle ("DocX.iOS")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("Managing Software")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("Managing Software")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]

// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.

[assembly: AssemblyVersion ("1.0.*")]

// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]


+ 0
- 89
DocX.iOS/System/Drawing/ColorTranslator.cs View File

@@ -1,89 +0,0 @@
using System;
using System.Drawing;

using Foundation;
using UIKit;

namespace System.Drawing
{
// ColorTranslator

public static class ColorTranslator
{
// FromHtml

public static Color FromHtml(string color, float alpha = 1.0f)
{
color = color.Replace ("#", "").Replace (" ", "").Trim ();

if (alpha > 1.0f)
{
alpha = 1.0f;
}

if (alpha < 0.0f)
{
alpha = 0.0f;
}

int A = 0, R = 0, G = 0, B = 0;

switch (color.Length)
{
case 3 : // #RGB
{
A = (int)(alpha * 255);

R = Convert.ToInt32(string.Format("{0}{0}", color.Substring(0, 1)), 16);

G = Convert.ToInt32(string.Format("{0}{0}", color.Substring(1, 1)), 16);

B = Convert.ToInt32(string.Format("{0}{0}", color.Substring(2, 1)), 16);

break;
}

case 4 : // #ARGB
{
A = Convert.ToInt32(string.Format("{0}{0}", color.Substring(0, 1)), 16);

R = Convert.ToInt32(string.Format("{0}{0}", color.Substring(1, 1)), 16);

G = Convert.ToInt32(string.Format("{0}{0}", color.Substring(2, 1)), 16);

B = Convert.ToInt32(string.Format("{0}{0}", color.Substring(3, 1)), 16);

break;
}

case 6 : // #RRGGBB
{
A = (int)(alpha * 255);

R = Convert.ToInt32(color.Substring(0, 2), 16);

G = Convert.ToInt32(color.Substring(2, 2), 16);

B = Convert.ToInt32(color.Substring(4, 2), 16);

break;
}

case 8 : // #RRGGBB
{
A = Convert.ToInt32(color.Substring(0, 2), 16);

R = Convert.ToInt32(color.Substring(2, 2), 16);

G = Convert.ToInt32(color.Substring(4, 2), 16);

B = Convert.ToInt32(color.Substring(6, 2), 16);

break;
}
}

return Color.FromArgb (A, R, G, B);
}
}
}

+ 0
- 20
DocX.iOS/System/Drawing/FontFamily.cs View File

@@ -1,20 +0,0 @@
using System;

namespace System.Drawing
{
// FontFamily

public class FontFamily : MarshalByRefObject
{
// properties

public string Name { get; private set; }

// constructor

public FontFamily (string name)
{
this.Name = name;
}
}
}

+ 0
- 85
DocX.iOS/System/Drawing/Image.cs View File

@@ -1,85 +0,0 @@
using System;
using System.IO;

using Foundation;
using UIKit;

namespace System.Drawing
{
// Image

public class Image : MarshalByRefObject, IDisposable
{
// FromStream

public static Image FromStream(Stream stream)
{
return new Image (stream);
}

// properties

public bool Disposed { get; private set; }

public int Height { get; private set; }

public int Width { get; private set; }

// constructor

private Image (Stream stream)
{
using (var image = UIImage.LoadFromData (NSData.FromStream (stream)))
{
this.Width = (int)image.Size.Width;

this.Height = (int)image.Size.Height;
}
}

// destructor

~Image()
{
Dispose(false);
}

// Dispose

public void Dispose()
{
this.Dispose(true);

GC.SuppressFinalize(this);
}

// Dispose

protected virtual void Dispose(bool disposing)
{
if (this.Disposed)
{
return;
}

try
{
try
{
if (disposing)
{
// dispose managed
}
}
finally
{
// dispose unmanaged
}
}
finally
{
this.Disposed = true;
}
}
}
}

+ 0
- 163
DocX.iOS/System/IO/Packaging/Check.cs View File

@@ -1,163 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using DocumentFormat.OpenXml.Packaging;

namespace System.IO.Packaging
{
internal static class Check
{
static void NotNull(object o, string name)
{
if (o == null)
throw new ArgumentNullException(name);
}

public static void ContentTypeIsValid(string contentType)
{
if (string.IsNullOrEmpty(contentType))
return;

// Must be in form of: type/subtype
int index = contentType.IndexOf('/');
bool result = (index > 0) && contentType.Length > (index + 1) && contentType.IndexOf('/', index + 1) == -1;

if (!result)
throw new ArgumentException("contentType", "contentType must be in the form of 'type/subtype'");
}

public static void Id(object id)
{
NotNull(id, "id");
}

public static void IdIsValid(string id)
{
if (id == null)
return;

// If the ID is a zero string, need to throw a ArgNullEx
if (id.Length == 0)
throw new ArgumentNullException("id", "Cannot be whitespace or empty");

// FIXME: I need to XSD parse this to make sure it's valid
// If it's not, throw an XmlException
}

private static bool EmptyOrBlank(string s)
{
return (s != null && (s == "" || s.Trim().Length == 0));
}

private static void PartUriDoesntEndWithSlash(Uri uri)
{
var s = !uri.IsAbsoluteUri ? uri.OriginalString
: uri.GetComponents(UriComponents.Path, UriFormat.UriEscaped);

// We allow '/' at uri's beggining.
if ((s.Length > 1) && s.EndsWith("/"))
{
throw new ArgumentException("Part URI cannot end with a forward slash.");
}
}

public static void Package(object package)
{
if (package == null)
throw new ArgumentNullException(nameof(package));
}


public static void PackageUri(object packageUri)
{
NotNull(packageUri, "packageUri");
}

public static void PackageUriIsValid(Uri packageUri)
{
if (!packageUri.IsAbsoluteUri)
throw new ArgumentException(nameof(packageUri), "Uri must be absolute");
}

public static void PackUriIsValid(Uri packUri)
{
if (!packUri.IsAbsoluteUri)
throw new ArgumentException(nameof(packUri), "PackUris must be absolute");

if (packUri.Scheme != PackUriHelper.UriSchemePack)
throw new ArgumentException(nameof(packUri), "Uri scheme is not a valid PackUri scheme");
}

public static void PartUri(object partUri)
{
if (partUri == null)
throw new ArgumentNullException(nameof(partUri));
}

public static void PartUriIsValid(Uri partUri)
{
if (!partUri.OriginalString.StartsWith("/"))
throw new ArgumentException("PartUris must start with '/'");

if (partUri.IsAbsoluteUri)
throw new ArgumentException("PartUris cannot be absolute");
}

public static void RelationshipTypeIsValid(string relationshipType)
{
if (relationshipType == null)
throw new ArgumentNullException(nameof(relationshipType));
if (EmptyOrBlank(relationshipType))
throw new ArgumentException("relationshipType", "Cannot be whitespace or empty");
}

public static void PartUri(Uri partUri)
{
if (partUri == null)
throw new ArgumentNullException(nameof(partUri));
if (partUri.IsAbsoluteUri)
throw new ArgumentException(nameof(partUri), "Absolute URIs are not supported");
if (string.IsNullOrEmpty(partUri.OriginalString))
throw new ArgumentException(nameof(partUri), "Part uri cannot be an empty string");
}

public static void PackUri(Uri packUri)
{
NotNull(packUri, "packUri");
}

public static void SourcePartUri(Uri sourcePartUri)
{
NotNull(sourcePartUri, "sourcePartUri");
PartUriDoesntEndWithSlash(sourcePartUri);
}

public static void TargetPartUri(Uri targetPartUri)
{
NotNull(targetPartUri, "targetPartUri");
PartUriDoesntEndWithSlash(targetPartUri);
}

public static void SourceUri(Uri sourceUri)
{
if (sourceUri == null)
throw new ArgumentNullException(nameof(sourceUri));
// if (sourceUri.IsAbsoluteUri)
// throw new ArgumentException ("sourceUri", "Absolute URIs are not supported");
if (string.IsNullOrEmpty(sourceUri.OriginalString))
throw new ArgumentException(nameof(sourceUri), "Part uri cannot be an empty string");
}

public static void TargetUri(Uri targetUri)
{
if (targetUri == null)
throw new ArgumentNullException(nameof(targetUri));
// if (targetUri.IsAbsoluteUri)
// throw new ArgumentException ("targetUri", "Absolute URIs are not supported");
if (string.IsNullOrEmpty(targetUri.OriginalString))
throw new ArgumentException(nameof(targetUri), "Part uri cannot be an empty string");
}
}
}

+ 0
- 17
DocX.iOS/System/IO/Packaging/CompressionOption.cs View File

@@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.IO.Packaging
{
public enum CompressionOption
{
NotCompressed = -1,
Normal,
Maximum,
Fast,
SuperFast,
}
}

+ 0
- 185
DocX.iOS/System/IO/Packaging/PackUriHelper.cs View File

@@ -1,185 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.IO.Packaging
{
public static class PackUriHelper
{
public static readonly string UriSchemePack = "pack";
static readonly Uri PackSchemeUri = new Uri("pack://", UriKind.Absolute);
static readonly char[] _escapedChars = new char[] { '%', ',', '?', '@' };


static PackUriHelper()
{
if (!UriParser.IsKnownScheme(UriSchemePack))
UriParser.Register(new PackUriParser(), UriSchemePack, -1);
}

public static int ComparePackUri(Uri firstPackUri, Uri secondPackUri)
{
if (firstPackUri == null)
return secondPackUri == null ? 0 : -1;
if (secondPackUri == null)
return 1;

Check.PackUriIsValid(firstPackUri);
Check.PackUriIsValid(secondPackUri);

// FIXME: What exactly is compared. Lets assume originalstring
return firstPackUri.OriginalString.CompareTo(secondPackUri.OriginalString);
}

public static int ComparePartUri(Uri firstPartUri, Uri secondPartUri)
{
if (firstPartUri == null)
return secondPartUri == null ? 0 : -1;
if (secondPartUri == null)
return 1;

Check.PartUriIsValid(firstPartUri);
Check.PartUriIsValid(secondPartUri);

return firstPartUri.OriginalString.CompareTo(secondPartUri.OriginalString);
}

public static Uri Create(Uri packageUri)
{
return Create(packageUri, null, null);
}

public static Uri Create(Uri packageUri, Uri partUri)
{
return Create(packageUri, partUri, null);
}

public static Uri Create(Uri packageUri, Uri partUri, string fragment)
{
Check.PackageUri(packageUri);
Check.PackageUriIsValid(packageUri);

if (partUri != null)
Check.PartUriIsValid(partUri);

if (fragment != null && (fragment.Length == 0 || fragment[0] != '#'))
throw new ArgumentException("Fragment", "Fragment must not be empty and must start with '#'");

// FIXME: Validate that partUri is a valid one? Must be relative, must start with '/'

// First replace the slashes, then escape the special characters
//string orig = packageUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
string orig = packageUri.OriginalString;

foreach (var ch in _escapedChars)
{
orig = !orig.Contains(ch.ToString()) ? orig : orig.Replace(ch.ToString(), Uri.HexEscape(ch));
}

orig = orig.Replace('/', ',');

if (partUri != null)
orig += partUri.OriginalString;

if ((fragment == null && partUri == null) && orig[orig.Length - 1] != '/')
orig += '/';

if (fragment != null)
orig += fragment;

return new Uri("pack://" + orig);
}

public static Uri CreatePartUri(Uri partUri)
{
Check.PartUri(partUri);

if (partUri.OriginalString[0] != '/')
partUri = new Uri("/" + partUri.ToString(), UriKind.Relative);
return partUri;
}

public static Uri GetNormalizedPartUri(Uri partUri)
{
Check.PartUri(partUri);
return new Uri(partUri.ToString().ToUpperInvariant(), UriKind.Relative);
}

public static Uri GetPackageUri(Uri packUri)
{
Check.PackUri(packUri);
Check.PackUriIsValid(packUri);

string s = packUri.Host.Replace(',', '/');
return new Uri(Uri.UnescapeDataString(s), UriKind.RelativeOrAbsolute);
}

public static Uri GetPartUri(Uri packUri)
{
Check.PackUri(packUri);
Check.PackUriIsValid(packUri);

if (string.IsNullOrEmpty(packUri.AbsolutePath) || packUri.AbsolutePath == "/")
return null;

return new Uri(packUri.AbsolutePath, UriKind.Relative);
}

public static Uri GetRelationshipPartUri(Uri partUri)
{
Check.PartUri(partUri);
Check.PartUriIsValid(partUri);

int index = partUri.OriginalString.LastIndexOf("/");
string s = partUri.OriginalString.Substring(0, index);
s += "/_rels" + partUri.OriginalString.Substring(index) + ".rels";
return new Uri(s, UriKind.Relative);
}

public static Uri GetRelativeUri(Uri sourcePartUri, Uri targetPartUri)
{
Check.SourcePartUri(sourcePartUri);
Check.TargetPartUri(targetPartUri);

Uri uri = new Uri("http://fake.com");
Uri a = new Uri(uri, sourcePartUri.OriginalString);
Uri b = new Uri(uri, targetPartUri.OriginalString);

return a.MakeRelativeUri(b);
}

public static Uri GetSourcePartUriFromRelationshipPartUri(Uri relationshipPartUri)
{
//Check.RelationshipPartUri (relationshipPartUri);
if (!IsRelationshipPartUri(relationshipPartUri))
throw new Exception("is not a relationship part!?");
return null;
}

public static bool IsRelationshipPartUri(Uri partUri)
{
Check.PartUri(partUri);
return partUri.OriginalString.StartsWith("/_rels") && partUri.OriginalString.EndsWith(".rels");
}

public static Uri ResolvePartUri(Uri sourcePartUri, Uri targetUri)
{
Check.SourcePartUri(sourcePartUri);
Check.TargetUri(targetUri);

Check.PartUriIsValid(sourcePartUri);
// commented out because on Android they are absolute file:///
// if (targetUri.IsAbsoluteUri)
// throw new ArgumentException("targetUri", "Absolute URIs are not supported");

Uri uri = new Uri("http://fake.com");
uri = new Uri(uri, sourcePartUri);
uri = new Uri(uri, targetUri);

// Trim out 'http://fake.com'
return new Uri(uri.OriginalString.Substring(15), UriKind.Relative);
}
}
}

+ 0
- 109
DocX.iOS/System/IO/Packaging/PackUriParser.cs View File

@@ -1,109 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.IO.Packaging
{
class PackUriParser : GenericUriParser
{
const string SchemaName = "pack";

StringBuilder builder = new StringBuilder();

public PackUriParser()
: base(GenericUriParserOptions.Default)
{
}

protected override string GetComponents(Uri uri, UriComponents components, UriFormat format)
{
string s = uri.OriginalString;
builder.Remove(0, builder.Length);

if ((components & UriComponents.Scheme) == UriComponents.Scheme)
{
int start = 0;
int end = s.IndexOf(':');
builder.Append(s, start, end - start);
}

if ((components & UriComponents.Host) == UriComponents.Host)
{
// Skip past pack://
int start = 7;
int end = s.IndexOf('/', start);
if (end == -1)
end = s.Length;

if (builder.Length > 0)
builder.Append("://");

builder.Append(s, start, end - start);
}

// Port is always -1, so i think i can ignore both Port and StrongPort
// Normally they'd get parsed here

if ((components & UriComponents.Path) == UriComponents.Path)
{
// Skip past pack://
int start = s.IndexOf('/', 7);
int end = s.IndexOf('?');
if (end == -1)
end = s.IndexOf('#');
if (end == -1)
end = s.Length;

if ((components & UriComponents.KeepDelimiter) != UriComponents.KeepDelimiter &&
builder.Length == 0)
start++;

if (start > 0) builder.Append(s, start, end - start);
}

if ((components & UriComponents.Query) == UriComponents.Query)
{
int index = s.IndexOf('?');

if (index != -1)
{
if ((components & UriComponents.KeepDelimiter) != UriComponents.KeepDelimiter &&
builder.Length == 0)
index++;

int fragIndex = s.IndexOf('#');
int end = fragIndex == -1 ? s.Length : fragIndex;
builder.Append(s, index, end - index);
}
}

if ((components & UriComponents.Fragment) == UriComponents.Fragment)
{
int index = s.IndexOf('#');

if (index != -1)
{
if ((components & UriComponents.KeepDelimiter) != UriComponents.KeepDelimiter &&
builder.Length == 0)
index++;

builder.Append(s, index, s.Length - index);
}
}

return builder.ToString();
}

protected override void InitializeAndValidate(Uri uri, out UriFormatException parsingError)
{
parsingError = null;
}

protected override UriParser OnNewUri()
{
return new PackUriParser();
}
}
}

+ 0
- 488
DocX.iOS/System/IO/Packaging/Package.cs View File

@@ -1,488 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
//using DocumentFormat.OpenXml.Packaging;

namespace System.IO.Packaging
{
public abstract class Package : IDisposable
{
internal const string RelationshipContentType = "application/vnd.openxmlformats-package.relationships+xml";
internal const string RelationshipNamespace = "http://schemas.openxmlformats.org/package/2006/relationships";
internal static readonly Uri RelationshipUri = new Uri("/_rels/.rels", UriKind.Relative);

private PackageProperties packageProperties;
private PackagePartCollection partsCollection;
private Dictionary<string, PackageRelationship> relationships;
private PackageRelationshipCollection relationshipsCollection = new PackageRelationshipCollection();
private Uri Uri = new Uri("/", UriKind.Relative);

private bool Disposed { get; set; }

public FileAccess FileOpenAccess { get; private set; }

public PackageProperties PackageProperties
{
get
{
// PackageProperties are loaded when the relationships are loaded.
// Therefore ensure we've already loaded the relationships.
int count = Relationships.Count;

if (packageProperties == null)
{
packageProperties = new PackagePropertiesPart();
packageProperties.Package = this;
}
return packageProperties;
}
}

private PackagePartCollection PartsCollection
{
get
{
if (partsCollection == null)
{
partsCollection = new PackagePartCollection();
partsCollection.Parts.AddRange(GetPartsCore());
}
return partsCollection;
}
}

private int RelationshipId { get; set; }

private Dictionary<string, PackageRelationship> Relationships
{
get
{
if (relationships == null)
{
LoadRelationships();
}
return relationships;
}
}

private bool Streaming { get; set; }


protected Package(FileAccess openFileAccess)
: this(openFileAccess, false)
{

}

protected Package(FileAccess openFileAccess, bool streaming)
{
FileOpenAccess = openFileAccess;
Streaming = streaming;
}


internal void CheckIsReadOnly()
{
if (FileOpenAccess == FileAccess.Read)
throw new IOException("Operation not valid when package is read-only");
}

public void Close()
{
// FIXME: Ensure that Flush is actually called before dispose
((IDisposable) this).Dispose();
}

public PackagePart CreatePart(Uri partUri, string contentType)
{
return CreatePart(partUri, contentType, CompressionOption.NotCompressed);
}

public PackagePart CreatePart(Uri partUri, string contentType, CompressionOption compressionOption)
{
CheckIsReadOnly();
Check.PartUri(partUri);
Check.ContentTypeIsValid(contentType);

if (PartExists(partUri))
throw new InvalidOperationException("This partUri is already contained in the package");

PackagePart part = CreatePartCore(partUri, contentType, compressionOption);
PartsCollection.Parts.Add(part);
return part;
}

protected abstract PackagePart CreatePartCore(Uri partUri, string contentType,
CompressionOption compressionOption);

public PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType)
{
return CreateRelationship(targetUri, targetMode, relationshipType, null);
}

public PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType,
string id)
{
return CreateRelationship(targetUri, targetMode, relationshipType, id, false);
}

internal PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType,
string id, bool loading)
{
if (!loading)
CheckIsReadOnly();

Check.TargetUri(targetUri);
if (targetUri.IsAbsoluteUri && targetMode == TargetMode.Internal)
throw new ArgumentException("TargetUri cannot be absolute for an internal relationship");

Check.RelationshipTypeIsValid(relationshipType);
Check.IdIsValid(id);

if (id == null)
id = NextId();

PackageRelationship r = new PackageRelationship(id, this, relationshipType, Uri, targetMode, targetUri);

if (!PartExists(RelationshipUri))
CreatePartCore(RelationshipUri, RelationshipContentType, CompressionOption.NotCompressed).IsRelationship
= true;

Relationships.Add(r.Id, r);
relationshipsCollection.Relationships.Add(r);

if (!loading)
{
using (Stream s = GetPart(RelationshipUri).GetStream())
WriteRelationships(relationships, s);
}

return r;
}


public void DeletePart(Uri partUri)
{
CheckIsReadOnly();
Check.PartUri(partUri);

PackagePart part = GetPart(partUri);
if (part != null)
{
if (part.Package == null)
throw new InvalidOperationException("This part has already been removed");

// FIXME: MS.NET doesn't remove the relationship part
// Instead it throws an exception if you try to use it
if (PartExists(part.RelationshipsPartUri))
GetPart(part.RelationshipsPartUri).Package = null;

part.Package = null;
DeletePartCore(partUri);
PartsCollection.Parts.RemoveAll(p => p.Uri == partUri);
}
}

protected abstract void DeletePartCore(Uri partUri);

public void DeleteRelationship(string id)
{
Check.Id(id);
CheckIsReadOnly();

Relationships.Remove(id);

relationshipsCollection.Relationships.RemoveAll(r => r.Id == id);
if (Relationships.Count > 0)
using (Stream s = GetPart(RelationshipUri).GetStream())
WriteRelationships(relationships, s);
else
DeletePart(RelationshipUri);
}

void IDisposable.Dispose()
{
if (!Disposed)
{
Flush();
Dispose(true);
Disposed = true;
}
}

protected virtual void Dispose(bool disposing)
{
// Nothing here needs to be disposed of
}

private bool flushing = false;

public void Flush()
{
if (FileOpenAccess == FileAccess.Read || flushing)
return;

flushing = true;

// Ensure we've loaded the relationships, parts and properties
int count = Relationships.Count;

if (packageProperties != null)
packageProperties.Flush();

FlushCore();

flushing = false;
}

protected abstract void FlushCore();

public PackagePart GetPart(Uri partUri)
{
Check.PartUri(partUri);
return GetPartCore(partUri);
}

protected abstract PackagePart GetPartCore(Uri partUri);

public PackagePartCollection GetParts()
{
PartsCollection.Parts.Clear();
PartsCollection.Parts.AddRange(GetPartsCore());
return PartsCollection;
}

protected abstract PackagePart[] GetPartsCore();

public PackageRelationship GetRelationship(string id)
{
return Relationships[id];
}

public PackageRelationshipCollection GetRelationships()
{
// Ensure the Relationships dict is instantiated first.
ICollection<PackageRelationship> rels = Relationships.Values;
relationshipsCollection.Relationships.Clear();
relationshipsCollection.Relationships.AddRange(rels);
return relationshipsCollection;
}

public PackageRelationshipCollection GetRelationshipsByType(string relationshipType)
{
PackageRelationshipCollection collection = new PackageRelationshipCollection();
foreach (PackageRelationship r in Relationships.Values)
if (r.RelationshipType == relationshipType)
collection.Relationships.Add(r);

return collection;
}

private void LoadRelationships()
{
relationships = new Dictionary<string, PackageRelationship>();

if (!PartExists(RelationshipUri))
return;

using (Stream stream = GetPart(RelationshipUri).GetStream())
{
XmlDocument doc = new XmlDocument();
doc.Load(stream);
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("rel", RelationshipNamespace);

foreach (XmlNode node in doc.SelectNodes("/rel:Relationships/*", manager))
{
TargetMode mode = TargetMode.Internal;
if (node.Attributes["TargetMode"] != null)
mode = (TargetMode) Enum.Parse(typeof (TargetMode), node.Attributes["TargetMode"].Value);

Uri uri;
try
{
uri = new Uri(node.Attributes["Target"].Value.ToString(), UriKind.Relative);
}
catch
{
uri = new Uri(node.Attributes["Target"].Value.ToString(), UriKind.Absolute);
}
CreateRelationship(uri,
mode,
node.Attributes["Type"].Value.ToString(),
node.Attributes["Id"].Value.ToString(),
true);
}

foreach (PackageRelationship r in relationships.Values)
{
if (r.RelationshipType == PackageProperties.NSPackagePropertiesRelation)
{
PackagePart part = GetPart(PackUriHelper.ResolvePartUri(Uri, r.TargetUri));
packageProperties = new PackagePropertiesPart();
packageProperties.Package = this;
packageProperties.Part = part;
packageProperties.LoadFrom(part.GetStream());
}
}
}
}

private string NextId()
{
while (true)
{
string s = "Re" + RelationshipId.ToString();
if (!Relationships.ContainsKey(s))
return s;

RelationshipId++;
}
}

public static Package Open(Stream stream)
{
return Open(stream, FileMode.Open);
}

public static Package Open(string path)
{
return Open(path, FileMode.OpenOrCreate);
}

public static Package Open(Stream stream, FileMode packageMode)
{
FileAccess access = packageMode == FileMode.Open ? FileAccess.Read : FileAccess.ReadWrite;
return Open(stream, packageMode, access);
}

public static Package Open(string path, FileMode packageMode)
{
return Open(path, packageMode, FileAccess.ReadWrite);
}

public static Package Open(Stream stream, FileMode packageMode, FileAccess packageAccess)
{
return Open(stream, packageMode, packageAccess, false);
}

private static Package Open(Stream stream, FileMode packageMode, FileAccess packageAccess, bool ownsStream)
{
return OpenCore(stream, packageMode, packageAccess, ownsStream);
}

public static Package Open(string path, FileMode packageMode, FileAccess packageAccess)
{
return Open(path, packageMode, packageAccess, FileShare.None);
}

public static Package Open(string path, FileMode packageMode, FileAccess packageAccess, FileShare packageShare)
{
if (packageShare != FileShare.Read && packageShare != FileShare.None)
throw new NotSupportedException("FileShare.Read and FileShare.None are the only supported options");

FileInfo info = new FileInfo(path);

// Bug - MS.NET appears to test for FileAccess.ReadWrite, not FileAccess.Write
if (packageAccess != FileAccess.ReadWrite && !info.Exists)
throw new ArgumentException("packageAccess", "Cannot create stream with FileAccess.Read");


if (info.Exists && packageMode == FileMode.OpenOrCreate && info.Length == 0)
throw new FileFormatException("Stream length cannot be zero with FileMode.Open");

Stream s = File.Open(path, packageMode, packageAccess, packageShare);
return Open(s, packageMode, packageAccess, true);
}

private static Package OpenCore(Stream stream, FileMode packageMode, FileAccess packageAccess, bool ownsStream)
{
if ((packageAccess & FileAccess.Read) == FileAccess.Read && !stream.CanRead)
throw new IOException("Stream does not support reading");

if ((packageAccess & FileAccess.Write) == FileAccess.Write && !stream.CanWrite)
throw new IOException("Stream does not support reading");

if (!stream.CanSeek)
throw new ArgumentException("stream", "Stream must support seeking");

if (packageMode == FileMode.Open && stream.Length == 0)
throw new FileFormatException("Stream length cannot be zero with FileMode.Open");

if (packageMode == FileMode.CreateNew && stream.Length > 0)
throw new IOException("Cannot use CreateNew when stream contains data");

if (packageMode == FileMode.Append || packageMode == FileMode.Truncate)
{
if (stream.CanWrite)
throw new NotSupportedException(string.Format("PackageMode.{0} is not supported", packageMode));
else
throw new IOException(string.Format("PackageMode.{0} is not supported", packageMode));
}

return new ZipPackage(packageAccess, ownsStream, stream);
}

public virtual bool PartExists(Uri partUri)
{
return GetPart(partUri) != null;
}

public bool RelationshipExists(string id)
{
return Relationships.ContainsKey(id);
}

internal static void WriteRelationships(Dictionary<string, PackageRelationship> relationships, Stream stream)
{
XmlDocument doc = new XmlDocument();
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("rel", RelationshipNamespace);

doc.AppendChild(doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""));

XmlNode root = doc.CreateNode(XmlNodeType.Element, "Relationships", RelationshipNamespace);
doc.AppendChild(root);

foreach (PackageRelationship relationship in relationships.Values)
{
XmlNode node = doc.CreateNode(XmlNodeType.Element, "Relationship", RelationshipNamespace);

XmlAttribute idAtt = doc.CreateAttribute("Id");
idAtt.Value = relationship.Id;
node.Attributes.Append(idAtt);

XmlAttribute targetAtt = doc.CreateAttribute("Target");
targetAtt.Value = relationship.TargetUri.ToString();
node.Attributes.Append(targetAtt);

if (relationship.TargetMode != TargetMode.Internal)
{
XmlAttribute modeAtt = doc.CreateAttribute("TargetMode");
modeAtt.Value = relationship.TargetMode.ToString();
node.Attributes.Append(modeAtt);
}
XmlAttribute typeAtt = doc.CreateAttribute("Type");
typeAtt.Value = relationship.RelationshipType;
node.Attributes.Append(typeAtt);

root.AppendChild(node);
}

using (XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8))
doc.WriteTo(writer);
}
}

internal class FileFormatException : Exception
{
public FileFormatException(string message): base(message)
{
}
}
}

+ 0
- 257
DocX.iOS/System/IO/Packaging/PackagePart.cs View File

@@ -1,257 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
//using DocumentFormat.OpenXml.Packaging;

namespace System.IO.Packaging
{
public abstract class PackagePart
{
string contentType;

internal bool IsRelationship { get; set; }

int relationshipId;
Dictionary<string, PackageRelationship> relationships;
PackageRelationshipCollection relationshipsCollection = new PackageRelationshipCollection();

Dictionary<string, PackageRelationship> Relationships
{
get
{
if (relationships == null)
{
relationships = new Dictionary<string, PackageRelationship>(StringComparer.OrdinalIgnoreCase);
if (Package.PartExists(RelationshipsPartUri))
using (Stream s = Package.GetPart(RelationshipsPartUri).GetStream())
LoadRelationships(relationships, s);
}

return relationships;
}
}
Stream PartStream { get; set; }

internal Uri RelationshipsPartUri
{
get;
set;
}

protected PackagePart(Package package, Uri partUri)
: this(package, partUri, null)
{

}

protected internal PackagePart(Package package, Uri partUri, string contentType)
: this(package, partUri, contentType, CompressionOption.Normal)
{

}

protected internal PackagePart(Package package, Uri partUri, string contentType, CompressionOption compressionOption)
{
Check.Package(package);
Check.PartUri(partUri);
Check.ContentTypeIsValid(contentType);

Package = package;
Uri = partUri;
ContentType = contentType;
CompressionOption = compressionOption;
RelationshipsPartUri = PackUriHelper.GetRelationshipPartUri(Uri);
}

public CompressionOption CompressionOption
{
get;
private set;
}

public string ContentType
{
get
{
if (contentType == null && (contentType = GetContentTypeCore()) == null)
throw new NotSupportedException("If contentType is not supplied in the constructor, GetContentTypeCore must be overridden");
return contentType;
}
private set
{
contentType = value;
}
}

public Package Package
{
get;
internal set;
}

public Uri Uri
{
get;
private set;
}

private void CheckIsRelationship()
{
if (IsRelationship)
throw new InvalidOperationException("A relationship cannot have relationships to other parts");
}

public PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType)
{
return CreateRelationship(targetUri, targetMode, relationshipType, null);
}

public PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType, string id)
{
return CreateRelationship(targetUri, targetMode, relationshipType, id, false);
}

private PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType, string id, bool loading)
{
//Package.CheckIsReadOnly();
Check.TargetUri(targetUri);
Check.RelationshipTypeIsValid(relationshipType);
Check.IdIsValid(id);

if (id == null)
id = NextId();

if (Relationships.ContainsKey(id))
throw new XmlException("A relationship with this ID already exists");

PackageRelationship r = new PackageRelationship(id, Package, relationshipType, Uri, targetMode, targetUri);
Relationships.Add(r.Id, r);

if (!loading)
WriteRelationships();
return r;
}

public void DeleteRelationship(string id)
{
Package.CheckIsReadOnly();
CheckIsRelationship();
Relationships.Remove(id);
WriteRelationships();
}

void LoadRelationships(Dictionary<string, PackageRelationship> relationships, Stream stream)
{
XmlDocument doc = new XmlDocument();
doc.Load(stream);
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("rel", Package.RelationshipNamespace);

foreach (XmlNode node in doc.SelectNodes("/rel:Relationships/*", manager))
{
TargetMode mode = TargetMode.Internal;
if (node.Attributes["TargetMode"] != null)
mode = (TargetMode)Enum.Parse(typeof(TargetMode), node.Attributes["TargetMode"].Value);

CreateRelationship(new Uri(node.Attributes["Target"].Value.ToString(), UriKind.RelativeOrAbsolute),
mode,
node.Attributes["Type"].Value.ToString(),
node.Attributes["Id"].Value.ToString(),
true);
}
}

public bool RelationshipExists(string id)
{
CheckIsRelationship();
return Relationships.ContainsKey(id);
}

public PackageRelationship GetRelationship(string id)
{
CheckIsRelationship();
return Relationships[id];
}

public PackageRelationshipCollection GetRelationships()
{
CheckIsRelationship();
relationshipsCollection.Relationships.Clear();
relationshipsCollection.Relationships.AddRange(Relationships.Values);
return relationshipsCollection;
}

public PackageRelationshipCollection GetRelationshipsByType(string relationshipType)
{
CheckIsRelationship();
PackageRelationshipCollection collection = new PackageRelationshipCollection();
foreach (PackageRelationship r in Relationships.Values)
if (r.RelationshipType == relationshipType)
collection.Relationships.Add(r);

return collection;
}

public Stream GetStream()
{
return GetStream(Package.FileOpenAccess == FileAccess.Read && !IsRelationship ? FileMode.Open : FileMode.OpenOrCreate);
}

public Stream GetStream(FileMode mode)
{
return GetStream(mode, IsRelationship ? FileAccess.ReadWrite : Package.FileOpenAccess);
}

public Stream GetStream(FileMode mode, FileAccess access)
{
bool notAllowed = mode == FileMode.Append || mode == FileMode.CreateNew || mode == FileMode.Truncate;
if (access != FileAccess.Read && notAllowed)
throw new ArgumentException(string.Format(string.Format("FileMode '{0}' not supported", mode)));

if (access == FileAccess.Read && (notAllowed || mode == FileMode.Create))
throw new IOException(string.Format("FileMode '{0}' not allowed on a readonly stream", mode));

return GetStreamCore(mode, access);
}

protected abstract Stream GetStreamCore(FileMode mode, FileAccess access);

protected virtual string GetContentTypeCore()
{
return null;
}

private string NextId()
{
while (true)
{
string s = "Re" + relationshipId.ToString();
if (!RelationshipExists(s))
return s;
relationshipId++;
}
}

void WriteRelationships()
{
bool exists = Package.PartExists(RelationshipsPartUri);
if (exists && Relationships.Count == 0)
{
Package.DeletePart(RelationshipsPartUri);
return;
}

if (!exists)
{
PackagePart part = Package.CreatePart(RelationshipsPartUri, Package.RelationshipContentType);
part.IsRelationship = true;
}
using (Stream s = Package.GetPart(RelationshipsPartUri).GetStream())
Package.WriteRelationships(Relationships, s);
}
}
}

+ 0
- 29
DocX.iOS/System/IO/Packaging/PackagePartCollection.cs View File

@@ -1,29 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.IO.Packaging
{
public class PackagePartCollection : IEnumerable<PackagePart>, IEnumerable
{
internal List<PackagePart> Parts { get; private set; }

internal PackagePartCollection()
{
Parts = new List<PackagePart>();
}

public IEnumerator<PackagePart> GetEnumerator()
{
return Parts.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return Parts.GetEnumerator();
}
}
}

+ 0
- 91
DocX.iOS/System/IO/Packaging/PackageProperties.cs View File

@@ -1,91 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace System.IO.Packaging
{
public abstract class PackageProperties : IDisposable
{
internal const string NSPackageProperties = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
internal const string NSPackagePropertiesRelation = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
internal const string PackagePropertiesContentType = "application/vnd.openxmlformats-package.core-properties+xml";


static int uuid;

protected PackageProperties()
{

}

public abstract string Category { get; set; }
public abstract string ContentStatus { get; set; }
public abstract string ContentType { get; set; }
public abstract DateTime? Created { get; set; }
public abstract string Creator { get; set; }
public abstract string Description { get; set; }
public abstract string Identifier { get; set; }
public abstract string Keywords { get; set; }
public abstract string Language { get; set; }
public abstract string LastModifiedBy { get; set; }
public abstract DateTime? LastPrinted { get; set; }
public abstract DateTime? Modified { get; set; }
internal Package Package { get; set; }
internal PackagePart Part { get; set; }
public abstract string Revision { get; set; }
public abstract string Subject { get; set; }
public abstract string Title { get; set; }
public abstract string Version { get; set; }


public void Dispose()
{
Dispose(true);
}

protected virtual void Dispose(bool disposing)
{
// Nothing
}

internal void Flush()
{
using (MemoryStream temp = new MemoryStream())
{
using (XmlTextWriter writer = new XmlTextWriter(temp, System.Text.Encoding.UTF8))
{
WriteTo(writer);
writer.Flush();
if (temp.Length == 0)
return;
}
}

if (Part == null)
{
int id = System.Threading.Interlocked.Increment(ref uuid);
Uri uri = new Uri(string.Format("/package/services/metadata/core-properties/{0}.psmdcp", id), UriKind.Relative);
Part = Package.CreatePart(uri, PackagePropertiesContentType);
PackageRelationship rel = Package.CreateRelationship(uri, TargetMode.Internal, NSPackagePropertiesRelation);
}

using (Stream s = Part.GetStream(FileMode.Create))
using (XmlTextWriter writer = new XmlTextWriter(s, System.Text.Encoding.UTF8))
WriteTo(writer);
}

internal virtual void LoadFrom(Stream stream)
{

}

internal virtual void WriteTo(XmlTextWriter writer)
{

}
}
}

+ 0
- 355
DocX.iOS/System/IO/Packaging/PackagePropertiesPart.cs View File

@@ -1,355 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace System.IO.Packaging
{
class PackagePropertiesPart : PackageProperties
{
const string NSDc = "http://purl.org/dc/elements/1.1/";
const string NSDcTerms = "http://purl.org/dc/terms/";
const string NSXsi = "http://www.w3.org/2001/XMLSchema-instance";

string category;
string contentStatus;
string contentType;
DateTime? created;
string creator;
string description;
string identifier;
string keywords;
string language;
string lastModifiedBy;
DateTime? lastPrinted;
DateTime? modified;
string revision;
string subject;
string title;
string version;

public PackagePropertiesPart()
{

}

public override string Category
{
get
{
return category;
}
set
{
Package.CheckIsReadOnly();
category = value;
}
}
public override string ContentStatus
{
get
{
return contentStatus;
}
set
{
Package.CheckIsReadOnly();
contentStatus = value;
}
}
public override string ContentType
{
get
{
return contentType;
}
set
{
Package.CheckIsReadOnly();
contentType = value;
}
}
public override DateTime? Created
{
get
{
return created;
}
set
{
Package.CheckIsReadOnly();
created = value;
}
}
public override string Creator
{
get
{
return creator;
}
set
{
Package.CheckIsReadOnly();
creator = value;
}
}
public override string Description
{
get
{
return description;
}
set
{
Package.CheckIsReadOnly();
description = value;
}
}
public override string Identifier
{
get
{
return identifier;
}
set
{
Package.CheckIsReadOnly();
identifier = value;
}
}
public override string Keywords
{
get
{
return keywords;
}
set
{
Package.CheckIsReadOnly();
keywords = value;
}
}
public override string Language
{
get
{
return language;
}
set
{
Package.CheckIsReadOnly();
language = value;
}
}
public override string LastModifiedBy
{
get
{
return lastModifiedBy;
}
set
{
Package.CheckIsReadOnly();
lastModifiedBy = value;
}
}
public override DateTime? LastPrinted
{
get
{
return lastPrinted;
}
set
{
Package.CheckIsReadOnly();
lastPrinted = value;
}
}
public override DateTime? Modified
{
get
{
return modified;
}
set
{
Package.CheckIsReadOnly();
modified = value;
}
}
public override string Revision
{
get
{
return revision;
}
set
{
Package.CheckIsReadOnly();
revision = value;
}
}
public override string Subject
{
get
{
return subject;
}
set
{
Package.CheckIsReadOnly();
subject = value;
}
}
public override string Title
{
get
{
return title;
}
set
{
Package.CheckIsReadOnly();
title = value;
}
}
public override string Version
{
get
{
return version;
}
set
{
Package.CheckIsReadOnly();
version = value;
}
}

internal override void LoadFrom(Stream stream)
{
if (stream.Length == 0)
return;

XmlDocument doc = new XmlDocument();
doc.Load(stream);

XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("prop", NSPackageProperties);
manager.AddNamespace("dc", NSDc);
manager.AddNamespace("dcterms", NSDcTerms);
manager.AddNamespace("xsi", NSXsi);

XmlNode node;
if ((node = doc.SelectSingleNode("prop:coreProperties/prop:category", manager)) != null)
category = node.InnerXml;
if ((node = doc.SelectSingleNode("prop:coreProperties/prop:contentStatus", manager)) != null)
contentStatus = node.InnerXml;
if ((node = doc.SelectSingleNode("prop:coreProperties/prop:contentType", manager)) != null)
contentType = node.InnerXml;
if ((node = doc.SelectSingleNode("prop:coreProperties/dcterms:created", manager)) != null)
created = DateTime.Parse(node.InnerXml);
if ((node = doc.SelectSingleNode("prop:coreProperties/dc:creator", manager)) != null)
creator = node.InnerXml;
if ((node = doc.SelectSingleNode("prop:coreProperties/dc:description", manager)) != null)
description = node.InnerXml;
if ((node = doc.SelectSingleNode("prop:coreProperties/dc:identifier", manager)) != null)
identifier = node.InnerXml;
if ((node = doc.SelectSingleNode("prop:coreProperties/prop:keywords", manager)) != null)
keywords = node.InnerXml;
if ((node = doc.SelectSingleNode("prop:coreProperties/dc:language", manager)) != null)
language = node.InnerXml;
if ((node = doc.SelectSingleNode("prop:coreProperties/prop:lastModifiedBy", manager)) != null)
lastModifiedBy = node.InnerXml;
if ((node = doc.SelectSingleNode("prop:coreProperties/prop:lastPrinted", manager)) != null)
lastPrinted = DateTime.Parse(node.InnerXml);
if ((node = doc.SelectSingleNode("prop:coreProperties/dcterms:modified", manager)) != null)
modified = DateTime.Parse(node.InnerXml);
if ((node = doc.SelectSingleNode("prop:coreProperties/prop:revision", manager)) != null)
revision = node.InnerXml;
if ((node = doc.SelectSingleNode("prop:coreProperties/dc:subject", manager)) != null)
subject = node.InnerXml;
if ((node = doc.SelectSingleNode("prop:coreProperties/dc:title", manager)) != null)
title = node.InnerXml;
if ((node = doc.SelectSingleNode("prop:coreProperties/prop:version", manager)) != null)
version = node.InnerXml;
}

internal override void WriteTo(XmlTextWriter writer)
{
XmlDocument doc = new XmlDocument();
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("prop", NSPackageProperties);
manager.AddNamespace("dc", NSDc);
manager.AddNamespace("dcterms", NSDcTerms);
manager.AddNamespace("xsi", NSXsi);

// Create XML declaration
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));

// Create root node with required namespace declarations
XmlNode coreProperties = doc.AppendChild(doc.CreateNode(XmlNodeType.Element, "coreProperties", NSPackageProperties));
coreProperties.Attributes.Append(doc.CreateAttribute("xmlns:dc")).Value = NSDc;
coreProperties.Attributes.Append(doc.CreateAttribute("xmlns:dcterms")).Value = NSDcTerms;
coreProperties.Attributes.Append(doc.CreateAttribute("xmlns:xsi")).Value = NSXsi;

// Create the children
if (Category != null)
coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "category", NSPackageProperties)).InnerXml = Category;
if (ContentStatus != null)
coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "contentStatus", NSPackageProperties)).InnerXml = ContentStatus;
if (ContentType != null)
coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "contentType", NSPackageProperties)).InnerXml = ContentType;
if (Created.HasValue)
{
XmlAttribute att = doc.CreateAttribute("xsi", "type", NSXsi);
att.Value = "dcterms:W3CDTF";

XmlNode created = coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dcterms", "created", NSDcTerms));
created.Attributes.Append(att);
created.InnerXml = Created.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss") + "Z";
}
if (Creator != null)
coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dc", "creator", NSDc)).InnerXml = Creator;
if (Description != null)
coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dc", "description", NSDc)).InnerXml = Description;
if (Identifier != null)
coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dc", "identifier", NSDc)).InnerXml = Identifier;
if (Keywords != null)
coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "keywords", NSPackageProperties)).InnerXml = Keywords;
if (Language != null)
coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dc", "language", NSDc)).InnerXml = Language;
if (LastModifiedBy != null)
coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "lastModifiedBy", NSPackageProperties)).InnerXml = LastModifiedBy;
if (LastPrinted.HasValue)
{
XmlNode lastPrinted = coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "lastPrinted", NSPackageProperties));

lastPrinted.InnerXml = LastPrinted.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss") + "Z";
}
if (Revision != null)
coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "revision", NSPackageProperties)).InnerXml = Revision;
if (Subject != null)
coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dc", "subject", NSDc)).InnerXml = Subject;
if (Title != null)
coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dc", "title", NSDc)).InnerXml = Title;
if (Version != null)
coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "version", NSPackageProperties)).InnerXml = Version;

if (Modified.HasValue)
{
XmlAttribute att = doc.CreateAttribute("xsi", "type", NSXsi);
att.Value = "dcterms:W3CDTF";

XmlNode modified = coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dcterms", "modified", NSDcTerms));
modified.Attributes.Append(att);
modified.InnerXml = Modified.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss") + "Z";
}

doc.WriteContentTo(writer);
}
}
}

+ 0
- 59
DocX.iOS/System/IO/Packaging/PackageRelationship.cs View File

@@ -1,59 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.IO.Packaging
{
public class PackageRelationship
{
internal PackageRelationship(string id, Package package, string relationshipType,
Uri sourceUri, TargetMode targetMode, Uri targetUri)
{
Check.IdIsValid(id);
Check.Package(package);
Check.RelationshipTypeIsValid(relationshipType);
Check.SourceUri(sourceUri);
Check.TargetUri(targetUri);

Id = id;
Package = package;
RelationshipType = relationshipType;
SourceUri = sourceUri;
TargetMode = targetMode;
TargetUri = targetUri;
}

public string Id
{
get;
private set;
}
public Package Package
{
get;
private set;
}
public string RelationshipType
{
get;
private set;
}
public Uri SourceUri
{
get;
private set;
}
public TargetMode TargetMode
{
get;
private set;
}
public Uri TargetUri
{
get;
private set;
}
}
}

+ 0
- 29
DocX.iOS/System/IO/Packaging/PackageRelationshipCollection.cs View File

@@ -1,29 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.IO.Packaging
{
public class PackageRelationshipCollection : IEnumerable<PackageRelationship>, IEnumerable
{
internal List<PackageRelationship> Relationships { get; private set; }

internal PackageRelationshipCollection()
{
Relationships = new List<PackageRelationship>();
}

public IEnumerator<PackageRelationship> GetEnumerator()
{
return Relationships.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}

+ 0
- 14
DocX.iOS/System/IO/Packaging/TargetMode.cs View File

@@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.IO.Packaging
{
public enum TargetMode
{
Internal,
External
}
}

+ 0
- 266
DocX.iOS/System/IO/Packaging/ZipPackage.cs View File

@@ -1,266 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using DocX.iOS.Zip;

namespace System.IO.Packaging
{
class UriComparer : IEqualityComparer<Uri>
{
public int GetHashCode(Uri uri)
{
return 1;
}

public bool Equals(Uri x, Uri y)
{
return x.OriginalString.Equals(y.OriginalString, StringComparison.OrdinalIgnoreCase);
}
}

public sealed class ZipPackage : Package
{
public ZipStorer Archive { get; set; }
private const string ContentNamespace = "http://schemas.openxmlformats.org/package/2006/content-types";
private const string ContentUri = "[Content_Types].xml";

bool OwnsStream
{
get;
set;
}

Dictionary<Uri, ZipPackagePart> parts;
internal Dictionary<Uri, MemoryStream> PartStreams = new Dictionary<Uri, MemoryStream>(new UriComparer());

internal Stream PackageStream { get; set; }

Dictionary<Uri, ZipPackagePart> Parts
{
get
{
if (parts == null)
LoadParts();
return parts;
}
}

internal ZipPackage(FileAccess access, bool ownsStream, Stream stream)
: base(access)
{
OwnsStream = ownsStream;
PackageStream = stream;
}

internal ZipPackage(FileAccess access, bool ownsStream, Stream stream, bool streaming)
: base(access, streaming)
{
OwnsStream = ownsStream;
PackageStream = stream;
}

protected override void Dispose(bool disposing)
{
foreach (Stream s in PartStreams.Values)
s.Close();

if (Archive != null) // GZE fixed bug where Archive == null
{
Archive.Close();
}

base.Dispose(disposing);

if (OwnsStream)
PackageStream.Close();
}

protected override void FlushCore()
{
// Ensure that all the data has been read out of the package
// stream already. Otherwise we'll lose data when we recreate the zip

foreach (ZipPackagePart part in Parts.Values)
{
part.GetStream();
}
if (!PackageStream.CanSeek)
return;
// Empty the package stream
PackageStream.Position = 0;
PackageStream.SetLength(0);

// Recreate the zip file
using (ZipStorer archive = ZipStorer.Create(PackageStream, "", false))
{

// Write all the part streams
foreach (ZipPackagePart part in Parts.Values)
{
Stream partStream = part.GetStream();
partStream.Seek(0, SeekOrigin.Begin);

archive.AddStream(ZipStorer.Compression.Deflate, part.Uri.ToString().Substring(1), partStream,
DateTime.UtcNow, "");
}

using (var ms = new MemoryStream())
{
WriteContentType(ms);
ms.Seek(0, SeekOrigin.Begin);

archive.AddStream(ZipStorer.Compression.Deflate, ContentUri, ms, DateTime.UtcNow, "");
}
}
}


protected override PackagePart CreatePartCore(Uri partUri, string contentType, CompressionOption compressionOption)
{
ZipPackagePart part = new ZipPackagePart(this, partUri, contentType, compressionOption);
Parts.Add(part.Uri, part);
return part;
}

protected override void DeletePartCore(Uri partUri)
{
Parts.Remove(partUri);
}

protected override PackagePart GetPartCore(Uri partUri)
{
ZipPackagePart part;
Parts.TryGetValue(partUri, out part);
return part;
}

protected override PackagePart[] GetPartsCore()
{
ZipPackagePart[] p = new ZipPackagePart[Parts.Count];
Parts.Values.CopyTo(p, 0);
return p;
}

void LoadParts()
{
parts = new Dictionary<Uri, ZipPackagePart>(new UriComparer());
try
{
PackageStream.Seek(0, SeekOrigin.Begin);
if (Archive == null)
{
Archive = ZipStorer.Open(PackageStream, FileAccess.Read, false);
}
List<ZipStorer.ZipFileEntry> dir = Archive.ReadCentralDir();

// Load the content type map file
XmlDocument doc = new XmlDocument();
var content = dir.FirstOrDefault(x => x.FilenameInZip == ContentUri);
using (var ms = new MemoryStream())
{
Archive.ExtractFile(content, ms);
ms.Seek(0, SeekOrigin.Begin);
doc.Load(ms);
}

XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("content", ContentNamespace);

// The file names in the zip archive are not prepended with '/'
foreach (var file in dir)
{
if (file.FilenameInZip.Equals(ContentUri, StringComparison.Ordinal))
continue;

XmlNode node;

if (file.FilenameInZip == RelationshipUri.ToString().Substring(1))
{
CreatePartCore(RelationshipUri, RelationshipContentType, CompressionOption.Normal);
continue;
}

string xPath = string.Format("/content:Types/content:Override[@PartName='/{0}']", file);
node = doc.SelectSingleNode(xPath, manager);

if (node == null)
{
string ext = Path.GetExtension(file.FilenameInZip);
if (ext.StartsWith("."))
ext = ext.Substring(1);
xPath = string.Format("/content:Types/content:Default[@Extension='{0}']", ext);
node = doc.SelectSingleNode(xPath, manager);
}

// What do i do if the node is null? This means some has tampered with the
// package file manually
if (node != null)
CreatePartCore(new Uri("/" + file, UriKind.Relative), node.Attributes["ContentType"].Value,
CompressionOption.Normal);
}
}
catch
{
// The archive is invalid - therefore no parts
}
}

void WriteContentType(Stream s)
{
XmlDocument doc = new XmlDocument();
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
Dictionary<string, string> mimes = new Dictionary<string, string>();

manager.AddNamespace("content", ContentNamespace);

doc.AppendChild(doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""));

XmlNode root = doc.CreateNode(XmlNodeType.Element, "Types", ContentNamespace);
doc.AppendChild(root);
foreach (ZipPackagePart part in Parts.Values)
{
XmlNode node = null;
string existingMimeType;

var extension = Path.GetExtension(part.Uri.OriginalString);
if (extension.Length > 0)
extension = extension.Substring(1);

if (!mimes.TryGetValue(extension, out existingMimeType))
{
node = doc.CreateNode(XmlNodeType.Element, "Default", ContentNamespace);

XmlAttribute ext = doc.CreateAttribute("Extension");
ext.Value = extension;
node.Attributes.Append(ext);
mimes[extension] = part.ContentType;
}
else if (part.ContentType != existingMimeType)
{
node = doc.CreateNode(XmlNodeType.Element, "Override", ContentNamespace);

XmlAttribute name = doc.CreateAttribute("PartName");
name.Value = part.Uri.ToString();
node.Attributes.Append(name);
}

if (node != null)
{
XmlAttribute contentType = doc.CreateAttribute("ContentType");
contentType.Value = part.ContentType;
node.Attributes.Prepend(contentType);

root.AppendChild(node);
}
}

XmlTextWriter writer = new XmlTextWriter(s, System.Text.Encoding.UTF8);
doc.WriteTo(writer);
writer.Flush();
}
}
}

+ 0
- 77
DocX.iOS/System/IO/Packaging/ZipPackagePart.cs View File

@@ -1,77 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocX.iOS.Zip;

namespace System.IO.Packaging
{
public sealed class ZipPackagePart : PackagePart
{
new ZipPackage Package
{
get { return (ZipPackage)base.Package; }
}

internal ZipPackagePart(Package package, Uri partUri)
: base(package, partUri)
{

}

internal ZipPackagePart(Package package, Uri partUri, string contentType)
: base(package, partUri, contentType)
{

}

internal ZipPackagePart(Package package, Uri partUri, string contentType, CompressionOption compressionOption)
: base(package, partUri, contentType, compressionOption)
{

}

protected override Stream GetStreamCore(FileMode mode, FileAccess access)
{
ZipPartStream zps;
MemoryStream stream;
if (Package.PartStreams.TryGetValue(Uri, out stream))
{
//zps = new ZipPartStream(Package, stream, access);
if (mode == FileMode.Create)
stream.SetLength(0);
return new ZipPartStream(Package, stream, access);
}

stream = new MemoryStream();
try
{
if (Package.Archive == null)
{
Package.Archive = ZipStorer.Open(Package.PackageStream, access, false);
}
List<ZipStorer.ZipFileEntry> dir = Package.Archive.ReadCentralDir();
foreach (ZipStorer.ZipFileEntry entry in dir)
{
if (entry.FilenameInZip != Uri.ToString().Substring(1))
continue;

Package.Archive.ExtractFile(entry, stream);
}
}
catch
{
// The zipfile is invalid, so just create the file
// as if it didn't exist
stream.SetLength(0);
}

Package.PartStreams.Add(Uri, stream);
if (mode == FileMode.Create)
stream.SetLength(0);
return new ZipPartStream(Package, stream, access);
}
}
}

+ 0
- 131
DocX.iOS/System/IO/Packaging/ZipPartStream.cs View File

@@ -1,131 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.IO.Packaging
{
internal class ZipPartStream : Stream
{
public MemoryStream BaseStream { get; private set; }
public ZipPackage Package { get; private set; }

public override bool CanRead
{
get
{
return BaseStream.CanRead;
}
}

public override bool CanSeek
{
get
{
return BaseStream.CanSeek;
}
}

public override bool CanTimeout
{
get { return BaseStream.CanTimeout; }
}

public override bool CanWrite
{
get { return Writeable; }
}

public override long Length
{
get { return BaseStream.Length; }
}

public override long Position
{
get;
set;
}

public bool Writeable
{
get;
set;
}

public override int WriteTimeout
{
get
{
return BaseStream.WriteTimeout;
}
set
{
BaseStream.WriteTimeout = value;
}
}

public override int ReadTimeout
{
get
{
return BaseStream.ReadTimeout;
}
set
{
BaseStream.ReadTimeout = value;
}
}

public ZipPartStream(ZipPackage package, MemoryStream stream, FileAccess access)
{
BaseStream = stream;
Package = package;
Writeable = access != FileAccess.Read;
}

public override void Flush()
{
// If the user flushes any of the part streams,
// we need to flush the entire package

// FIXME: Ensure that this actually happens with a testcase
// ...if possible
// Package.Flush();
}

public override int Read(byte[] buffer, int offset, int count)
{
Seek(Position, SeekOrigin.Begin);
int read = BaseStream.Read(buffer, offset, count);
Position += read;
return read;
}

public override long Seek(long offset, SeekOrigin origin)
{
Position = BaseStream.Seek(offset, origin);
return Position;
}

public override void SetLength(long value)
{
if (!CanWrite)
throw new InvalidOperationException("Stream is not writeable");

BaseStream.SetLength(value);
}

public override void Write(byte[] buffer, int offset, int count)
{
if (!CanWrite)
throw new InvalidOperationException("Stream is not writeable");

Seek(Position, SeekOrigin.Begin);
BaseStream.Write(buffer, offset, count);
Position += count;
}
}
}

+ 0
- 758
DocX.iOS/Zip/ZipStorer.cs View File

@@ -1,758 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DocX.iOS.Zip
{
/// <summary>
/// Unique class for compression/decompression file. Represents a Zip file.
/// </summary>
public class ZipStorer : IDisposable
{
/// <summary>
/// Compression method enumeration
/// </summary>
public enum Compression : ushort
{
/// <summary>Uncompressed storage</summary>
Store = 0,
/// <summary>Deflate compression method</summary>
Deflate = 8
}

/// <summary>
/// Represents an entry in Zip file directory
/// </summary>
public struct ZipFileEntry
{
/// <summary>Compression method</summary>
public Compression Method;
/// <summary>Full path and filename as stored in Zip</summary>
public string FilenameInZip;
/// <summary>Original file size</summary>
public uint FileSize;
/// <summary>Compressed file size</summary>
public uint CompressedSize;
/// <summary>Offset of header information inside Zip storage</summary>
public uint HeaderOffset;
/// <summary>Offset of file inside Zip storage</summary>
public uint FileOffset;
/// <summary>Size of header information</summary>
public uint HeaderSize;
/// <summary>32-bit checksum of entire file</summary>
public uint Crc32;
/// <summary>Last modification time of file</summary>
public DateTime ModifyTime;
/// <summary>User comment for file</summary>
public string Comment;
/// <summary>True if UTF8 encoding for filename and comments, false if default (CP 437)</summary>
public bool EncodeUTF8;

/// <summary>Overriden method</summary>
/// <returns>Filename in Zip</returns>
public override string ToString()
{
return this.FilenameInZip;
}
}

#region Public fields
/// <summary>True if UTF8 encoding for filename and comments, false if default (CP 437)</summary>
public bool EncodeUTF8 = false;
/// <summary>Force deflate algotithm even if it inflates the stored file. Off by default.</summary>
public bool ForceDeflating = false;
#endregion

#region Private fields
// List of files to store
private List<ZipFileEntry> Files = new List<ZipFileEntry>();
// Filename of storage file
private string FileName;
// Stream object of storage file
private Stream ZipFileStream;
private bool OwnsStream = true;
// General comment
private string Comment = "";
// Central dir image
private byte[] CentralDirImage = null;
// Existing files in zip
private ushort ExistingFiles = 0;
// File access for Open method
private FileAccess Access;
// Static CRC32 Table
private static UInt32[] CrcTable = null;
// Default filename encoder
private static Encoding DefaultEncoding = Encoding.GetEncoding(437);
#endregion

#region Public methods
// Static constructor. Just invoked once in order to create the CRC32 lookup table.
static ZipStorer()
{
// Generate CRC32 table
CrcTable = new UInt32[256];
for (int i = 0; i < CrcTable.Length; i++)
{
UInt32 c = (UInt32)i;
for (int j = 0; j < 8; j++)
{
if ((c & 1) != 0)
c = 3988292384 ^ (c >> 1);
else
c >>= 1;
}
CrcTable[i] = c;
}
}
/// <summary>
/// Method to create a new storage file
/// </summary>
/// <param name="_filename">Full path of Zip file to create</param>
/// <param name="_comment">General comment for Zip file</param>
/// <returns>A valid ZipStorer object</returns>
public static ZipStorer Create(string _filename, string _comment)
{
Stream stream = new FileStream(_filename, FileMode.Create, FileAccess.ReadWrite);

ZipStorer zip = Create(stream, _comment, true);
zip.Comment = _comment;
zip.FileName = _filename;

return zip;
}
/// <summary>
/// Method to create a new zip storage in a stream
/// </summary>
/// <param name="_stream"></param>
/// <param name="_comment"></param>
/// <returns>A valid ZipStorer object</returns>
public static ZipStorer Create(Stream _stream, string _comment, bool _ownsStream = false)
{
ZipStorer zip = new ZipStorer();
zip.Comment = _comment;
zip.ZipFileStream = _stream;
zip.OwnsStream = _ownsStream;
zip.Access = FileAccess.Write;

return zip;
}
/// <summary>
/// Method to open an existing storage file
/// </summary>
/// <param name="_filename">Full path of Zip file to open</param>
/// <param name="_access">File access mode as used in FileStream constructor</param>
/// <returns>A valid ZipStorer object</returns>
public static ZipStorer Open(string _filename, FileAccess _access)
{
Stream stream = (Stream)new FileStream(_filename, FileMode.Open, _access == FileAccess.Read ? FileAccess.Read : FileAccess.ReadWrite);

ZipStorer zip = Open(stream, _access, true);
zip.FileName = _filename;

return zip;
}
/// <summary>
/// Method to open an existing storage from stream
/// </summary>
/// <param name="_stream">Already opened stream with zip contents</param>
/// <param name="_access">File access mode for stream operations</param>
/// <returns>A valid ZipStorer object</returns>
public static ZipStorer Open(Stream _stream, FileAccess _access, bool _ownsStream = false)
{
if (!_stream.CanSeek && _access != FileAccess.Read)
throw new InvalidOperationException("Stream cannot seek");

ZipStorer zip = new ZipStorer();
//zip.FileName = _filename;
zip.ZipFileStream = _stream;
zip.OwnsStream = _ownsStream;
zip.Access = _access;

if (zip.ReadFileInfo())
return zip;

throw new System.IO.InvalidDataException();
}
/// <summary>
/// Add full contents of a file into the Zip storage
/// </summary>
/// <param name="_method">Compression method</param>
/// <param name="_pathname">Full path of file to add to Zip storage</param>
/// <param name="_filenameInZip">Filename and path as desired in Zip directory</param>
/// <param name="_comment">Comment for stored file</param>
public void AddFile(Compression _method, string _pathname, string _filenameInZip, string _comment)
{
if (Access == FileAccess.Read)
throw new InvalidOperationException("Writing is not alowed");

FileStream stream = new FileStream(_pathname, FileMode.Open, FileAccess.Read);
AddStream(_method, _filenameInZip, stream, File.GetLastWriteTime(_pathname), _comment);
stream.Close();
}
/// <summary>
/// Add full contents of a stream into the Zip storage
/// </summary>
/// <param name="_method">Compression method</param>
/// <param name="_filenameInZip">Filename and path as desired in Zip directory</param>
/// <param name="_source">Stream object containing the data to store in Zip</param>
/// <param name="_modTime">Modification time of the data to store</param>
/// <param name="_comment">Comment for stored file</param>
public void AddStream(Compression _method, string _filenameInZip, Stream _source, DateTime _modTime, string _comment)
{
if (Access == FileAccess.Read)
throw new InvalidOperationException("Writing is not alowed");

long offset;
if (this.Files.Count == 0)
offset = 0;
else
{
ZipFileEntry last = this.Files[this.Files.Count - 1];
offset = last.HeaderOffset + last.HeaderSize;
}

// Prepare the fileinfo
ZipFileEntry zfe = new ZipFileEntry();
zfe.Method = _method;
zfe.EncodeUTF8 = this.EncodeUTF8;
zfe.FilenameInZip = NormalizedFilename(_filenameInZip);
zfe.Comment = (_comment == null ? "" : _comment);

// Even though we write the header now, it will have to be rewritten, since we don't know compressed size or crc.
zfe.Crc32 = 0; // to be updated later
zfe.HeaderOffset = (uint)this.ZipFileStream.Position; // offset within file of the start of this local record
zfe.ModifyTime = _modTime;

// Write local header
WriteLocalHeader(ref zfe);
zfe.FileOffset = (uint)this.ZipFileStream.Position;

// Write file to zip (store)
Store(ref zfe, _source);
_source.Close();

this.UpdateCrcAndSizes(ref zfe);

Files.Add(zfe);
}
/// <summary>
/// Updates central directory (if pertinent) and close the Zip storage
/// </summary>
/// <remarks>This is a required step, unless automatic dispose is used</remarks>
public void Close()
{
if (this.Access != FileAccess.Read)
{
uint centralOffset = (uint)this.ZipFileStream.Position;
uint centralSize = 0;

if (this.CentralDirImage != null)
this.ZipFileStream.Write(CentralDirImage, 0, CentralDirImage.Length);

for (int i = 0; i < Files.Count; i++)
{
long pos = this.ZipFileStream.Position;
this.WriteCentralDirRecord(Files[i]);
centralSize += (uint)(this.ZipFileStream.Position - pos);
}

if (this.CentralDirImage != null)
this.WriteEndRecord(centralSize + (uint)CentralDirImage.Length, centralOffset);
else
this.WriteEndRecord(centralSize, centralOffset);
}

if (this.ZipFileStream != null && ZipFileStream.CanSeek)
{
this.ZipFileStream.Flush();

// GZE added ownsStream, to prevent premature closure

if (this.OwnsStream)
{
this.ZipFileStream.Dispose();
}

this.ZipFileStream = null;
}
}
/// <summary>
/// Read all the file records in the central directory
/// </summary>
/// <returns>List of all entries in directory</returns>
public List<ZipFileEntry> ReadCentralDir()
{
if (this.CentralDirImage == null)
throw new InvalidOperationException("Central directory currently does not exist");

List<ZipFileEntry> result = new List<ZipFileEntry>();

for (int pointer = 0; pointer < this.CentralDirImage.Length; )
{
uint signature = BitConverter.ToUInt32(CentralDirImage, pointer);
if (signature != 0x02014b50)
break;

bool encodeUTF8 = (BitConverter.ToUInt16(CentralDirImage, pointer + 8) & 0x0800) != 0;
ushort method = BitConverter.ToUInt16(CentralDirImage, pointer + 10);
uint modifyTime = BitConverter.ToUInt32(CentralDirImage, pointer + 12);
uint crc32 = BitConverter.ToUInt32(CentralDirImage, pointer + 16);
uint comprSize = BitConverter.ToUInt32(CentralDirImage, pointer + 20);
uint fileSize = BitConverter.ToUInt32(CentralDirImage, pointer + 24);
ushort filenameSize = BitConverter.ToUInt16(CentralDirImage, pointer + 28);
ushort extraSize = BitConverter.ToUInt16(CentralDirImage, pointer + 30);
ushort commentSize = BitConverter.ToUInt16(CentralDirImage, pointer + 32);
uint headerOffset = BitConverter.ToUInt32(CentralDirImage, pointer + 42);
uint headerSize = (uint)(46 + filenameSize + extraSize + commentSize);

Encoding encoder = encodeUTF8 ? Encoding.UTF8 : DefaultEncoding;

ZipFileEntry zfe = new ZipFileEntry();
zfe.Method = (Compression)method;
zfe.FilenameInZip = encoder.GetString(CentralDirImage, pointer + 46, filenameSize);
zfe.FileOffset = GetFileOffset(headerOffset);
zfe.FileSize = fileSize;
zfe.CompressedSize = comprSize;
zfe.HeaderOffset = headerOffset;
zfe.HeaderSize = headerSize;
zfe.Crc32 = crc32;
zfe.ModifyTime = DosTimeToDateTime(modifyTime);
if (commentSize > 0)
zfe.Comment = encoder.GetString(CentralDirImage, pointer + 46 + filenameSize + extraSize, commentSize);

result.Add(zfe);
pointer += (46 + filenameSize + extraSize + commentSize);
}

return result;
}
/// <summary>
/// Copy the contents of a stored file into a physical file
/// </summary>
/// <param name="_zfe">Entry information of file to extract</param>
/// <param name="_filename">Name of file to store uncompressed data</param>
/// <returns>True if success, false if not.</returns>
/// <remarks>Unique compression methods are Store and Deflate</remarks>
public bool ExtractFile(ZipFileEntry _zfe, string _filename)
{
// Make sure the parent directory exist
string path = System.IO.Path.GetDirectoryName(_filename);

if (!Directory.Exists(path))
Directory.CreateDirectory(path);
// Check it is directory. If so, do nothing
if (Directory.Exists(_filename))
return true;

Stream output = new FileStream(_filename, FileMode.Create, FileAccess.Write);
bool result = ExtractFile(_zfe, output);
if (result)
output.Close();

File.SetCreationTime(_filename, _zfe.ModifyTime);
File.SetLastWriteTime(_filename, _zfe.ModifyTime);

return result;
}
/// <summary>
/// Copy the contents of a stored file into an opened stream
/// </summary>
/// <param name="_zfe">Entry information of file to extract</param>
/// <param name="_stream">Stream to store the uncompressed data</param>
/// <returns>True if success, false if not.</returns>
/// <remarks>Unique compression methods are Store and Deflate</remarks>
public bool ExtractFile(ZipFileEntry _zfe, Stream _stream)
{
if (!_stream.CanWrite)
throw new InvalidOperationException("Stream cannot be written");

// check signature
byte[] signature = new byte[4];
this.ZipFileStream.Seek(_zfe.HeaderOffset, SeekOrigin.Begin);
this.ZipFileStream.Read(signature, 0, 4);
if (BitConverter.ToUInt32(signature, 0) != 0x04034b50)
return false;

// Select input stream for inflating or just reading
Stream inStream;
if (_zfe.Method == Compression.Store)
inStream = this.ZipFileStream;
else if (_zfe.Method == Compression.Deflate)
inStream = new DeflateStream(this.ZipFileStream, CompressionMode.Decompress, true);
else
return false;

// Buffered copy
byte[] buffer = new byte[16384];
this.ZipFileStream.Seek(_zfe.FileOffset, SeekOrigin.Begin);
uint bytesPending = _zfe.FileSize;
while (bytesPending > 0)
{
int bytesRead = inStream.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length));
_stream.Write(buffer, 0, bytesRead);
bytesPending -= (uint)bytesRead;
}
_stream.Flush();

if (_zfe.Method == Compression.Deflate)
inStream.Dispose();
return true;
}
/// <summary>
/// Removes one of many files in storage. It creates a new Zip file.
/// </summary>
/// <param name="_zip">Reference to the current Zip object</param>
/// <param name="_zfes">List of Entries to remove from storage</param>
/// <returns>True if success, false if not</returns>
/// <remarks>This method only works for storage of type FileStream</remarks>
public static bool RemoveEntries(ref ZipStorer _zip, List<ZipFileEntry> _zfes)
{
if (!(_zip.ZipFileStream is FileStream))
throw new InvalidOperationException("RemoveEntries is allowed just over streams of type FileStream");


//Get full list of entries
List<ZipFileEntry> fullList = _zip.ReadCentralDir();

//In order to delete we need to create a copy of the zip file excluding the selected items
string tempZipName = Path.GetTempFileName();
string tempEntryName = Path.GetTempFileName();

try
{
ZipStorer tempZip = ZipStorer.Create(tempZipName, string.Empty);

foreach (ZipFileEntry zfe in fullList)
{
if (!_zfes.Contains(zfe))
{
if (_zip.ExtractFile(zfe, tempEntryName))
{
tempZip.AddFile(zfe.Method, tempEntryName, zfe.FilenameInZip, zfe.Comment);
}
}
}
_zip.Close();
tempZip.Close();

File.Delete(_zip.FileName);
File.Move(tempZipName, _zip.FileName);

_zip = ZipStorer.Open(_zip.FileName, _zip.Access);
}
catch
{
return false;
}
finally
{
if (File.Exists(tempZipName))
File.Delete(tempZipName);
if (File.Exists(tempEntryName))
File.Delete(tempEntryName);
}
return true;
}
#endregion

#region Private methods
// Calculate the file offset by reading the corresponding local header
private uint GetFileOffset(uint _headerOffset)
{
byte[] buffer = new byte[2];

this.ZipFileStream.Seek(_headerOffset + 26, SeekOrigin.Begin);
this.ZipFileStream.Read(buffer, 0, 2);
ushort filenameSize = BitConverter.ToUInt16(buffer, 0);
this.ZipFileStream.Read(buffer, 0, 2);
ushort extraSize = BitConverter.ToUInt16(buffer, 0);

return (uint)(30 + filenameSize + extraSize + _headerOffset);
}
/* Local file header:
local file header signature 4 bytes (0x04034b50)
version needed to extract 2 bytes
general purpose bit flag 2 bytes
compression method 2 bytes
last mod file time 2 bytes
last mod file date 2 bytes
crc-32 4 bytes
compressed size 4 bytes
uncompressed size 4 bytes
filename length 2 bytes
extra field length 2 bytes

filename (variable size)
extra field (variable size)
*/
private void WriteLocalHeader(ref ZipFileEntry _zfe)
{
long pos = this.ZipFileStream.Position;
Encoding encoder = _zfe.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
byte[] encodedFilename = encoder.GetBytes(_zfe.FilenameInZip);

this.ZipFileStream.Write(new byte[] { 80, 75, 3, 4, 20, 0 }, 0, 6); // No extra header
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)(_zfe.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method
this.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4); // zipping date and time
this.ZipFileStream.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0, 12); // unused CRC, un/compressed size, updated later
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // filename length
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length

this.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length);
_zfe.HeaderSize = (uint)(this.ZipFileStream.Position - pos);
}
/* Central directory's File header:
central file header signature 4 bytes (0x02014b50)
version made by 2 bytes
version needed to extract 2 bytes
general purpose bit flag 2 bytes
compression method 2 bytes
last mod file time 2 bytes
last mod file date 2 bytes
crc-32 4 bytes
compressed size 4 bytes
uncompressed size 4 bytes
filename length 2 bytes
extra field length 2 bytes
file comment length 2 bytes
disk number start 2 bytes
internal file attributes 2 bytes
external file attributes 4 bytes
relative offset of local header 4 bytes

filename (variable size)
extra field (variable size)
file comment (variable size)
*/
private void WriteCentralDirRecord(ZipFileEntry _zfe)
{
Encoding encoder = _zfe.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
byte[] encodedFilename = encoder.GetBytes(_zfe.FilenameInZip);
byte[] encodedComment = encoder.GetBytes(_zfe.Comment);

this.ZipFileStream.Write(new byte[] { 80, 75, 1, 2, 23, 0xB, 20, 0 }, 0, 8);
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)(_zfe.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method
this.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4); // zipping date and time
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4); // file CRC
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4); // compressed file size
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4); // uncompressed file size
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // Filename in zip
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2);

this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // disk=0
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // file type: binary
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // Internal file attributes
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0x8100), 0, 2); // External file attributes (normal/readable)
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.HeaderOffset), 0, 4); // Offset of header

this.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length);
this.ZipFileStream.Write(encodedComment, 0, encodedComment.Length);
}
/* End of central dir record:
end of central dir signature 4 bytes (0x06054b50)
number of this disk 2 bytes
number of the disk with the
start of the central directory 2 bytes
total number of entries in
the central dir on this disk 2 bytes
total number of entries in
the central dir 2 bytes
size of the central directory 4 bytes
offset of start of central
directory with respect to
the starting disk number 4 bytes
zipfile comment length 2 bytes
zipfile comment (variable size)
*/
private void WriteEndRecord(uint _size, uint _offset)
{
Encoding encoder = this.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
byte[] encodedComment = encoder.GetBytes(this.Comment);

this.ZipFileStream.Write(new byte[] { 80, 75, 5, 6, 0, 0, 0, 0 }, 0, 8);
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)Files.Count + ExistingFiles), 0, 2);
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)Files.Count + ExistingFiles), 0, 2);
this.ZipFileStream.Write(BitConverter.GetBytes(_size), 0, 4);
this.ZipFileStream.Write(BitConverter.GetBytes(_offset), 0, 4);
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2);
this.ZipFileStream.Write(encodedComment, 0, encodedComment.Length);
}
// Copies all source file into storage file
private void Store(ref ZipFileEntry _zfe, Stream _source)
{
byte[] buffer = new byte[16384];
int bytesRead;
uint totalRead = 0;
Stream outStream;

long posStart = this.ZipFileStream.Position;
long sourceStart = _source.Position;

if (_zfe.Method == Compression.Store)
outStream = this.ZipFileStream;
else
outStream = new DeflateStream(this.ZipFileStream, CompressionMode.Compress, true);

_zfe.Crc32 = 0 ^ 0xffffffff;

do
{
bytesRead = _source.Read(buffer, 0, buffer.Length);
totalRead += (uint)bytesRead;
if (bytesRead > 0)
{
outStream.Write(buffer, 0, bytesRead);

for (uint i = 0; i < bytesRead; i++)
{
_zfe.Crc32 = ZipStorer.CrcTable[(_zfe.Crc32 ^ buffer[i]) & 0xFF] ^ (_zfe.Crc32 >> 8);
}
}
} while (bytesRead == buffer.Length);
outStream.Flush();

if (_zfe.Method == Compression.Deflate)
outStream.Dispose();

_zfe.Crc32 ^= 0xffffffff;
_zfe.FileSize = totalRead;
_zfe.CompressedSize = (uint)(this.ZipFileStream.Position - posStart);

// Verify for real compression
if (_zfe.Method == Compression.Deflate && !this.ForceDeflating && _source.CanSeek && _zfe.CompressedSize > _zfe.FileSize)
{
// Start operation again with Store algorithm
_zfe.Method = Compression.Store;
this.ZipFileStream.Position = posStart;
this.ZipFileStream.SetLength(posStart);
_source.Position = sourceStart;
this.Store(ref _zfe, _source);
}
}
/* DOS Date and time:
MS-DOS date. The date is a packed value with the following format. Bits Description
0-4 Day of the month (1–31)
5-8 Month (1 = January, 2 = February, and so on)
9-15 Year offset from 1980 (add 1980 to get actual year)
MS-DOS time. The time is a packed value with the following format. Bits Description
0-4 Second divided by 2
5-10 Minute (0–59)
11-15 Hour (0–23 on a 24-hour clock)
*/
private uint DateTimeToDosTime(DateTime _dt)
{
return (uint)(
(_dt.Second / 2) | (_dt.Minute << 5) | (_dt.Hour << 11) |
(_dt.Day << 16) | (_dt.Month << 21) | ((_dt.Year - 1980) << 25));
}
private DateTime DosTimeToDateTime(uint _dt)
{
return new DateTime(
(int)(_dt >> 25) + 1980,
(int)(_dt >> 21) & 15,
(int)(_dt >> 16) & 31,
(int)(_dt >> 11) & 31,
(int)(_dt >> 5) & 63,
(int)(_dt & 31) * 2);
}

/* CRC32 algorithm
The 'magic number' for the CRC is 0xdebb20e3.
The proper CRC pre and post conditioning
is used, meaning that the CRC register is
pre-conditioned with all ones (a starting value
of 0xffffffff) and the value is post-conditioned by
taking the one's complement of the CRC residual.
If bit 3 of the general purpose flag is set, this
field is set to zero in the local header and the correct
value is put in the data descriptor and in the central
directory.
*/
private void UpdateCrcAndSizes(ref ZipFileEntry _zfe)
{
long lastPos = this.ZipFileStream.Position; // remember position

this.ZipFileStream.Position = _zfe.HeaderOffset + 8;
this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method

this.ZipFileStream.Position = _zfe.HeaderOffset + 14;
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4); // Update CRC
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4); // Compressed size
this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4); // Uncompressed size

this.ZipFileStream.Position = lastPos; // restore position
}
// Replaces backslashes with slashes to store in zip header
private string NormalizedFilename(string _filename)
{
string filename = _filename.Replace('\\', '/');

int pos = filename.IndexOf(':');
if (pos >= 0)
filename = filename.Remove(0, pos + 1);

return filename.Trim('/');
}
// Reads the end-of-central-directory record
private bool ReadFileInfo()
{
if (this.ZipFileStream.Length < 22)
return false;

try
{
this.ZipFileStream.Seek(-17, SeekOrigin.End);
BinaryReader br = new BinaryReader(this.ZipFileStream);
do
{
this.ZipFileStream.Seek(-5, SeekOrigin.Current);
UInt32 sig = br.ReadUInt32();
if (sig == 0x06054b50)
{
this.ZipFileStream.Seek(6, SeekOrigin.Current);

UInt16 entries = br.ReadUInt16();
Int32 centralSize = br.ReadInt32();
UInt32 centralDirOffset = br.ReadUInt32();
UInt16 commentSize = br.ReadUInt16();

// check if comment field is the very last data in file
if (this.ZipFileStream.Position + commentSize != this.ZipFileStream.Length)
return false;

// Copy entire central directory to a memory buffer
this.ExistingFiles = entries;
this.CentralDirImage = new byte[centralSize];
this.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin);
this.ZipFileStream.Read(this.CentralDirImage, 0, centralSize);

// Leave the pointer at the begining of central dir, to append new files
this.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin);
return true;
}
} while (this.ZipFileStream.Position > 0);
}
catch { }

return false;
}
#endregion

#region IDisposable Members
/// <summary>
/// Closes the Zip file stream
/// </summary>
public void Dispose()
{
this.Close();
}
#endregion
}
}

+ 0
- 53
DocX.sln View File

@@ -1,53 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{DF41F5CE-8BCB-40CC-835F-54A3DB7D802F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DocX", "DocX\DocX.csproj", "{E863D072-AA8B-4108-B5F1-785241B37F67}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitTests", "UnitTests\UnitTests.csproj", "{3EA73F1C-9E0B-4ED5-B04B-6C043D14D1AA}"
ProjectSection(ProjectDependencies) = postProject
{E863D072-AA8B-4108-B5F1-785241B37F67} = {E863D072-AA8B-4108-B5F1-785241B37F67}
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Examples", "Examples\Examples.csproj", "{F3022BB7-0E40-4C80-A495-37FEAF3671AB}"
ProjectSection(ProjectDependencies) = postProject
{E863D072-AA8B-4108-B5F1-785241B37F67} = {E863D072-AA8B-4108-B5F1-785241B37F67}
EndProjectSection
EndProject
Project("{7CF6DF6D-3B04-46F8-A40B-537D21BCA0B4}") = "Documentation", "Documentation\Documentation.shfbproj", "{1EB1EE8F-9978-425B-A742-533DCCEB4811}"
ProjectSection(ProjectDependencies) = postProject
{E863D072-AA8B-4108-B5F1-785241B37F67} = {E863D072-AA8B-4108-B5F1-785241B37F67}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E863D072-AA8B-4108-B5F1-785241B37F67}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E863D072-AA8B-4108-B5F1-785241B37F67}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E863D072-AA8B-4108-B5F1-785241B37F67}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E863D072-AA8B-4108-B5F1-785241B37F67}.Release|Any CPU.Build.0 = Release|Any CPU
{3EA73F1C-9E0B-4ED5-B04B-6C043D14D1AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3EA73F1C-9E0B-4ED5-B04B-6C043D14D1AA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3EA73F1C-9E0B-4ED5-B04B-6C043D14D1AA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3EA73F1C-9E0B-4ED5-B04B-6C043D14D1AA}.Release|Any CPU.Build.0 = Release|Any CPU
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Release|Any CPU.Build.0 = Release|Any CPU
{1EB1EE8F-9978-425B-A742-533DCCEB4811}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1EB1EE8F-9978-425B-A742-533DCCEB4811}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1EB1EE8F-9978-425B-A742-533DCCEB4811}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(TestCaseManagementSettings) = postSolution
CategoryFile = DocX.vsmdi
EndGlobalSection
EndGlobal

+ 0
- 10
DocX.vssscc View File

@@ -1,10 +0,0 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROJECT"
}

+ 0
- 13
DocX/Bookmark.cs View File

@@ -1,13 +0,0 @@
namespace Novacode
{
public class Bookmark
{
public string Name { get; set; }
public Paragraph Paragraph { get; set; }
public void SetText(string newText)
{
Paragraph.ReplaceAtBookmark(newText, Name);
}
}
}

+ 0
- 17
DocX/BookmarkCollection.cs View File

@@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Novacode
{
public class BookmarkCollection : List<Bookmark>
{
public Bookmark this[string name]
{
get
{
return this.FirstOrDefault(bookmark => string.Equals(bookmark.Name, name, StringComparison.CurrentCultureIgnoreCase));
}
}
}
}

+ 0
- 31
DocX/Border.cs View File

@@ -1,31 +0,0 @@
using System.Drawing;
namespace Novacode
{
/// <summary>
/// Represents a border of a table or table cell
/// Added by lckuiper @ 20101117
/// </summary>
public class Border
{
public BorderStyle Tcbs { get; set; }
public BorderSize Size { get; set; }
public int Space { get; set; }
public Color Color { get; set; }
public Border()
{
this.Tcbs = BorderStyle.Tcbs_single;
this.Size = BorderSize.one;
this.Space = 0;
this.Color = Color.Black;
}
public Border(BorderStyle tcbs, BorderSize size, int space, Color color)
{
this.Tcbs = tcbs;
this.Size = size;
this.Space = space;
this.Color = color;
}
}
}

+ 0
- 118
DocX/Charts/Axis.cs View File

@@ -1,118 +0,0 @@
using System;
using System.Xml.Linq;
namespace Novacode
{
/// <summary>
/// Axis base class
/// </summary>
public abstract class Axis
{
/// <summary>
/// ID of this Axis
/// </summary>
public String Id
{
get
{
return Xml.Element(XName.Get("axId", DocX.c.NamespaceName)).Attribute(XName.Get("val")).Value;
}
}
/// <summary>
/// Return true if this axis is visible
/// </summary>
public Boolean IsVisible
{
get
{
return Xml.Element(XName.Get("delete", DocX.c.NamespaceName)).Attribute(XName.Get("val")).Value == "0";
}
set
{
if (value)
Xml.Element(XName.Get("delete", DocX.c.NamespaceName)).Attribute(XName.Get("val")).Value = "0";
else
Xml.Element(XName.Get("delete", DocX.c.NamespaceName)).Attribute(XName.Get("val")).Value = "1";
}
}
/// <summary>
/// Axis xml element
/// </summary>
internal XElement Xml { get; set; }
internal Axis(XElement xml)
{
Xml = xml;
}
public Axis(String id)
{ }
}
/// <summary>
/// Represents Category Axes
/// </summary>
public class CategoryAxis : Axis
{
internal CategoryAxis(XElement xml)
: base(xml)
{ }
public CategoryAxis(String id)
: base(id)
{
Xml = XElement.Parse(String.Format(
@"<c:catAx xmlns:c=""http://schemas.openxmlformats.org/drawingml/2006/chart"">
<c:axId val=""{0}""/>
<c:scaling>
<c:orientation val=""minMax""/>
</c:scaling>
<c:delete val=""0""/>
<c:axPos val=""b""/>
<c:majorTickMark val=""out""/>
<c:minorTickMark val=""none""/>
<c:tickLblPos val=""nextTo""/>
<c:crossAx val=""154227840""/>
<c:crosses val=""autoZero""/>
<c:auto val=""1""/>
<c:lblAlgn val=""ctr""/>
<c:lblOffset val=""100""/>
<c:noMultiLvlLbl val=""0""/>
</c:catAx>", id));
}
}
/// <summary>
/// Represents Values Axes
/// </summary>
public class ValueAxis : Axis
{
internal ValueAxis(XElement xml)
: base(xml)
{ }
public ValueAxis(String id)
: base(id)
{
Xml = XElement.Parse(String.Format(
@"<c:valAx xmlns:c=""http://schemas.openxmlformats.org/drawingml/2006/chart"">
<c:axId val=""{0}""/>
<c:scaling>
<c:orientation val=""minMax""/>
</c:scaling>
<c:delete val=""0""/>
<c:axPos val=""l""/>
<c:numFmt sourceLinked=""0"" formatCode=""General""/>
<c:majorGridlines/>
<c:majorTickMark val=""out""/>
<c:minorTickMark val=""none""/>
<c:tickLblPos val=""nextTo""/>
<c:crossAx val=""148921728""/>
<c:crosses val=""autoZero""/>
<c:crossBetween val=""between""/>
</c:valAx>", id));
}
}
}

+ 0
- 102
DocX/Charts/BarChart.cs View File

@@ -1,102 +0,0 @@
using System;
using System.Xml.Linq;
namespace Novacode
{
/// <summary>
/// This element contains the 2-D bar or column series on this chart.
/// 21.2.2.16 barChart (Bar Charts)
/// </summary>
public class BarChart : Chart
{
/// <summary>
/// Specifies the possible directions for a bar chart.
/// </summary>
public BarDirection BarDirection
{
get
{
return XElementHelpers.GetValueToEnum<BarDirection>(
ChartXml.Element(XName.Get("barDir", DocX.c.NamespaceName)));
}
set
{
XElementHelpers.SetValueFromEnum<BarDirection>(
ChartXml.Element(XName.Get("barDir", DocX.c.NamespaceName)), value);
}
}
/// <summary>
/// Specifies the possible groupings for a bar chart.
/// </summary>
public BarGrouping BarGrouping
{
get
{
return XElementHelpers.GetValueToEnum<BarGrouping>(
ChartXml.Element(XName.Get("grouping", DocX.c.NamespaceName)));
}
set
{
XElementHelpers.SetValueFromEnum<BarGrouping>(
ChartXml.Element(XName.Get("grouping", DocX.c.NamespaceName)), value);
}
}
/// <summary>
/// Specifies that its contents contain a percentage between 0% and 500%.
/// </summary>
public Int32 GapWidth
{
get
{
return Convert.ToInt32(
ChartXml.Element(XName.Get("gapWidth", DocX.c.NamespaceName)).Attribute(XName.Get("val")).Value);
}
set
{
if ((value < 1) || (value > 500))
throw new ArgumentException("GapWidth lay between 0% and 500%!");
ChartXml.Element(XName.Get("gapWidth", DocX.c.NamespaceName)).Attribute(XName.Get("val")).Value = value.ToString();
}
}
protected override XElement CreateChartXml()
{
return XElement.Parse(
@"<c:barChart xmlns:c=""http://schemas.openxmlformats.org/drawingml/2006/chart"">
<c:barDir val=""col""/>
<c:grouping val=""clustered""/>
<c:gapWidth val=""150""/>
</c:barChart>");
}
}
/// <summary>
/// Specifies the possible directions for a bar chart.
/// 21.2.3.3 ST_BarDir (Bar Direction)
/// </summary>
public enum BarDirection
{
[XmlName("col")]
Column,
[XmlName("bar")]
Bar
}
/// <summary>
/// Specifies the possible groupings for a bar chart.
/// 21.2.3.4 ST_BarGrouping (Bar Grouping)
/// </summary>
public enum BarGrouping
{
[XmlName("clustered")]
Clustered,
[XmlName("percentStacked")]
PercentStacked,
[XmlName("stacked")]
Stacked,
[XmlName("standard")]
Standard
}
}

+ 0
- 477
DocX/Charts/Chart.cs View File

@@ -1,477 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Collections;
using System.Drawing;
namespace Novacode
{
/// <summary>
/// Represents every Chart in this document.
/// </summary>
public abstract class Chart
{
protected XElement ChartXml { get; private set; }
protected XElement ChartRootXml { get; private set; }
/// <summary>
/// The xml representation of this chart
/// </summary>
public XDocument Xml { get; private set; }
#region Series
/// <summary>
/// Chart's series
/// </summary>
public List<Series> Series
{
get
{
List<Series> series = new List<Series>();
int indx = 1;
foreach (XElement element in ChartXml.Elements(XName.Get("ser", DocX.c.NamespaceName)))
{
element.Add(new XElement(XName.Get("idx", DocX.c.NamespaceName)), (indx++).ToString());
series.Add(new Series(element));
}
return series;
}
}
/// <summary>
/// Return maximum count of series
/// </summary>
public virtual Int16 MaxSeriesCount { get { return Int16.MaxValue; } }
/// <summary>
/// Add a new series to this chart
/// </summary>
public void AddSeries(Series series)
{
int serCount = ChartXml.Elements(XName.Get("ser", DocX.c.NamespaceName)).Count();
if (serCount == MaxSeriesCount)
throw new InvalidOperationException("Maximum series for this chart is" + MaxSeriesCount.ToString() + "and have exceeded!");
// Sourceman 16.04.2015 - Every Series needs to have an order and index element for being processed by Word 2013
series.Xml.AddFirst(
new XElement(XName.Get("order", DocX.c.NamespaceName),
new XAttribute(XName.Get("val"), (serCount + 1).ToString())));
series.Xml.AddFirst(
new XElement(XName.Get("idx", DocX.c.NamespaceName),
new XAttribute(XName.Get("val"), (serCount + 1).ToString())));
ChartXml.Add(series.Xml);
}
#endregion
#region Legend
/// <summary>
/// Chart's legend.
/// If legend doesn't exist property is null.
/// </summary>
public ChartLegend Legend { get; private set; }
/// <summary>
/// Add standart legend to the chart.
/// </summary>
public void AddLegend()
{
AddLegend(ChartLegendPosition.Right, false);
}
/// <summary>
/// Add a legend with parameters to the chart.
/// </summary>
public void AddLegend(ChartLegendPosition position, Boolean overlay)
{
if (Legend != null)
RemoveLegend();
Legend = new ChartLegend(position, overlay);
//ChartRootXml.Add(Legend.Xml);
// Sourceman: seems to be necessary to keep track of the order of elements as defined in the schema (Word 2013)
ChartRootXml.Element(XName.Get("plotArea", DocX.c.NamespaceName)).AddAfterSelf(Legend.Xml);
}
/// <summary>
/// Remove the legend from the chart.
/// </summary>
public void RemoveLegend()
{
Legend.Xml.Remove();
Legend = null;
}
#endregion
#region Axis
/// <summary>
/// Represents the category axis
/// </summary>
public CategoryAxis CategoryAxis { get; private set; }
/// <summary>
/// Represents the values axis
/// </summary>
public ValueAxis ValueAxis { get; private set; }
/// <summary>
/// Represents existing the axis
/// </summary>
public virtual Boolean IsAxisExist { get { return true; } }
#endregion
/// <summary>
/// Get or set 3D view for this chart
/// </summary>
public Boolean View3D
{
get
{
return ChartXml.Name.LocalName.Contains("3D");
}
set
{
if (value)
{
if (!View3D)
{
String currentName = ChartXml.Name.LocalName;
ChartXml.Name = XName.Get(currentName.Replace("Chart", "3DChart"), DocX.c.NamespaceName);
}
}
else
{
if (View3D)
{
String currentName = ChartXml.Name.LocalName;
ChartXml.Name = XName.Get(currentName.Replace("3DChart", "Chart"), DocX.c.NamespaceName);
}
}
}
}
/// <summary>
/// Specifies how blank cells shall be plotted on a chart
/// </summary>
public DisplayBlanksAs DisplayBlanksAs
{
get
{
return XElementHelpers.GetValueToEnum<DisplayBlanksAs>(
ChartRootXml.Element(XName.Get("dispBlanksAs", DocX.c.NamespaceName)));
}
set
{
XElementHelpers.SetValueFromEnum<DisplayBlanksAs>(
ChartRootXml.Element(XName.Get("dispBlanksAs", DocX.c.NamespaceName)), value);
}
}
/// <summary>
/// Create an Chart for this document
/// </summary>
public Chart()
{
// Create global xml
Xml = XDocument.Parse
(@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<c:chartSpace xmlns:c=""http://schemas.openxmlformats.org/drawingml/2006/chart"" xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"">
<c:roundedCorners val=""0""/>
<c:chart>
<c:autoTitleDeleted val=""0""/>
<c:plotVisOnly val=""1""/>
<c:dispBlanksAs val=""gap""/>
<c:showDLblsOverMax val=""0""/>
</c:chart>
</c:chartSpace>");
// Create a real chart xml in an inheritor
ChartXml = CreateChartXml();
// Create result plotarea element
XElement plotAreaXml = new XElement(
XName.Get("plotArea", DocX.c.NamespaceName),
new XElement(XName.Get("layout", DocX.c.NamespaceName)),
ChartXml);
// Set labels
XElement dLblsXml = XElement.Parse(
@"<c:dLbls xmlns:c=""http://schemas.openxmlformats.org/drawingml/2006/chart"">
<c:showLegendKey val=""0""/>
<c:showVal val=""0""/>
<c:showCatName val=""0""/>
<c:showSerName val=""0""/>
<c:showPercent val=""0""/>
<c:showBubbleSize val=""0""/>
<c:showLeaderLines val=""1""/>
</c:dLbls>");
ChartXml.Add(dLblsXml);
// if axes exists, create their
if (IsAxisExist)
{
CategoryAxis = new CategoryAxis("148921728");
ValueAxis = new ValueAxis("154227840");
XElement axIDcatXml = XElement.Parse(String.Format(
@"<c:axId val=""{0}"" xmlns:c=""http://schemas.openxmlformats.org/drawingml/2006/chart""/>", CategoryAxis.Id));
XElement axIDvalXml = XElement.Parse(String.Format(
@"<c:axId val=""{0}"" xmlns:c=""http://schemas.openxmlformats.org/drawingml/2006/chart""/>", ValueAxis.Id));
// Sourceman: seems to be necessary to keep track of the order of elements as defined in the schema (Word 2013)
var insertPoint = ChartXml.Element(XName.Get("gapWidth", DocX.c.NamespaceName));
if (insertPoint != null) {
insertPoint.AddAfterSelf(axIDvalXml);
insertPoint.AddAfterSelf(axIDcatXml);
} else {
ChartXml.Add(axIDcatXml);
ChartXml.Add(axIDvalXml);
}
plotAreaXml.Add(CategoryAxis.Xml);
plotAreaXml.Add(ValueAxis.Xml);
}
ChartRootXml = Xml.Root.Element(XName.Get("chart", DocX.c.NamespaceName));
//ChartRootXml.Add(plotAreaXml);
ChartRootXml.Element(XName.Get("autoTitleDeleted", DocX.c.NamespaceName)).AddAfterSelf(plotAreaXml);
}
/// <summary>
/// An abstract method which creates the current chart xml
/// </summary>
protected abstract XElement CreateChartXml();
}
/// <summary>
/// Represents a chart series
/// </summary>
public class Series
{
private XElement strCache;
private XElement numCache;
/// <summary>
/// Series xml element
/// </summary>
internal XElement Xml { get; private set; }
public Color Color
{
get
{
XElement colorElement = Xml.Element(XName.Get("spPr", DocX.c.NamespaceName));
if (colorElement == null)
return Color.Transparent;
else
return Color.FromArgb(Int32.Parse(
colorElement.Element(XName.Get("solidFill", DocX.a.NamespaceName)).Element(XName.Get("srgbClr", DocX.a.NamespaceName)).Attribute(XName.Get("val")).Value,
System.Globalization.NumberStyles.HexNumber));
}
set
{
XElement colorElement = Xml.Element(XName.Get("spPr", DocX.c.NamespaceName));
if (colorElement != null)
colorElement.Remove();
colorElement = new XElement(
XName.Get("spPr", DocX.c.NamespaceName),
new XElement(
XName.Get("solidFill", DocX.a.NamespaceName),
new XElement(
XName.Get("srgbClr", DocX.a.NamespaceName),
new XAttribute(XName.Get("val"), value.ToHex()))));
Xml.Element(XName.Get("tx", DocX.c.NamespaceName)).AddAfterSelf(colorElement);
}
}
internal Series(XElement xml)
{
Xml = xml;
strCache = xml.Element(XName.Get("cat", DocX.c.NamespaceName)).Element(XName.Get("strRef", DocX.c.NamespaceName)).Element(XName.Get("strCache", DocX.c.NamespaceName));
numCache = xml.Element(XName.Get("val", DocX.c.NamespaceName)).Element(XName.Get("numRef", DocX.c.NamespaceName)).Element(XName.Get("numCache", DocX.c.NamespaceName));
}
public Series(String name)
{
strCache = new XElement(XName.Get("strCache", DocX.c.NamespaceName));
numCache = new XElement(XName.Get("numCache", DocX.c.NamespaceName));
Xml = new XElement(
XName.Get("ser", DocX.c.NamespaceName),
new XElement(
XName.Get("tx", DocX.c.NamespaceName),
new XElement(
XName.Get("strRef", DocX.c.NamespaceName),
new XElement(XName.Get("f", DocX.c.NamespaceName), ""),
new XElement(
XName.Get("strCache", DocX.c.NamespaceName),
new XElement(
XName.Get("pt", DocX.c.NamespaceName),
new XAttribute(XName.Get("idx"), "0"),
new XElement(XName.Get("v", DocX.c.NamespaceName), name)
)))),
new XElement(XName.Get("invertIfNegative", DocX.c.NamespaceName), "0"),
new XElement(
XName.Get("cat", DocX.c.NamespaceName),
new XElement(XName.Get("strRef", DocX.c.NamespaceName),
new XElement(XName.Get("f", DocX.c.NamespaceName), ""),
strCache)),
new XElement(
XName.Get("val", DocX.c.NamespaceName),
new XElement(XName.Get("numRef", DocX.c.NamespaceName),
new XElement(XName.Get("f", DocX.c.NamespaceName), ""),
numCache))
);
}
public void Bind(ICollection list, String categoryPropertyName, String valuePropertyName)
{
XElement ptCount = new XElement(XName.Get("ptCount", DocX.c.NamespaceName), new XAttribute(XName.Get("val"), list.Count));
XElement formatCode = new XElement(XName.Get("formatCode", DocX.c.NamespaceName), "General");
strCache.RemoveAll();
numCache.RemoveAll();
strCache.Add(ptCount);
numCache.Add(formatCode);
numCache.Add(ptCount);
Int32 index = 0;
XElement pt;
foreach (var item in list)
{
pt = new XElement(XName.Get("pt", DocX.c.NamespaceName), new XAttribute(XName.Get("idx"), index),
new XElement(XName.Get("v", DocX.c.NamespaceName), item.GetType().GetProperty(categoryPropertyName).GetValue(item, null)));
strCache.Add(pt);
pt = new XElement(XName.Get("pt", DocX.c.NamespaceName), new XAttribute(XName.Get("idx"), index),
new XElement(XName.Get("v", DocX.c.NamespaceName), item.GetType().GetProperty(valuePropertyName).GetValue(item, null)));
numCache.Add(pt);
index++;
}
}
public void Bind(IList categories, IList values)
{
if (categories.Count != values.Count)
throw new ArgumentException("Categories count must equal to Values count");
XElement ptCount = new XElement(XName.Get("ptCount", DocX.c.NamespaceName), new XAttribute(XName.Get("val"), categories.Count));
XElement formatCode = new XElement(XName.Get("formatCode", DocX.c.NamespaceName), "General");
strCache.RemoveAll();
numCache.RemoveAll();
strCache.Add(ptCount);
numCache.Add(formatCode);
numCache.Add(ptCount);
XElement pt;
for (int index = 0; index < categories.Count; index++)
{
pt = new XElement(XName.Get("pt", DocX.c.NamespaceName), new XAttribute(XName.Get("idx"), index),
new XElement(XName.Get("v", DocX.c.NamespaceName), categories[index].ToString()));
strCache.Add(pt);
pt = new XElement(XName.Get("pt", DocX.c.NamespaceName), new XAttribute(XName.Get("idx"), index),
new XElement(XName.Get("v", DocX.c.NamespaceName), values[index].ToString()));
numCache.Add(pt);
}
}
}
/// <summary>
/// Represents a chart legend
/// More: http://msdn.microsoft.com/ru-ru/library/cc845123.aspx
/// </summary>
public class ChartLegend
{
/// <summary>
/// Legend xml element
/// </summary>
internal XElement Xml { get; private set; }
/// <summary>
/// Specifies that other chart elements shall be allowed to overlap this chart element
/// </summary>
public Boolean Overlay
{
get { return Xml.Element(XName.Get("overlay", DocX.c.NamespaceName)).Attribute("val").Value == "1"; }
set { Xml.Element(XName.Get("overlay", DocX.c.NamespaceName)).Attribute("val").Value = GetOverlayValue(value); }
}
/// <summary>
/// Specifies the possible positions for a legend
/// </summary>
public ChartLegendPosition Position
{
get
{
return XElementHelpers.GetValueToEnum<ChartLegendPosition>(
Xml.Element(XName.Get("legendPos", DocX.c.NamespaceName)));
}
set
{
XElementHelpers.SetValueFromEnum<ChartLegendPosition>(
Xml.Element(XName.Get("legendPos", DocX.c.NamespaceName)), value);
}
}
internal ChartLegend(ChartLegendPosition position, Boolean overlay)
{
Xml = new XElement(
XName.Get("legend", DocX.c.NamespaceName),
new XElement(XName.Get("legendPos", DocX.c.NamespaceName), new XAttribute("val", XElementHelpers.GetXmlNameFromEnum<ChartLegendPosition>(position))),
new XElement(XName.Get("overlay", DocX.c.NamespaceName), new XAttribute("val", GetOverlayValue(overlay)))
);
}
/// <summary>
/// ECMA-376, page 3840
/// 21.2.2.132 overlay (Overlay)
/// </summary>
private String GetOverlayValue(Boolean overlay)
{
if (overlay)
return "1";
else
return "0";
}
}
/// <summary>
/// Specifies the possible positions for a legend.
/// 21.2.3.24 ST_LegendPos (Legend Position)
/// </summary>
public enum ChartLegendPosition
{
[XmlName("t")]
Top,
[XmlName("b")]
Bottom,
[XmlName("l")]
Left,
[XmlName("r")]
Right,
[XmlName("tr")]
TopRight
}
/// <summary>
/// Specifies the possible ways to display blanks.
/// 21.2.3.10 ST_DispBlanksAs (Display Blanks As)
/// </summary>
public enum DisplayBlanksAs
{
[XmlName("gap")]
Gap,
[XmlName("span")]
Span,
[XmlName("zero")]
Zero
}
}

+ 0
- 50
DocX/Charts/LineChart.cs View File

@@ -1,50 +0,0 @@
using System.Xml.Linq;
namespace Novacode
{
/// <summary>
/// This element contains the 2-D line chart series.
/// 21.2.2.97 lineChart (Line Charts)
/// </summary>
public class LineChart: Chart
{
/// <summary>
/// Specifies the kind of grouping for a column, line, or area chart.
/// </summary>
public Grouping Grouping
{
get
{
return XElementHelpers.GetValueToEnum<Grouping>(
ChartXml.Element(XName.Get("grouping", DocX.c.NamespaceName)));
}
set
{
XElementHelpers.SetValueFromEnum<Grouping>(
ChartXml.Element(XName.Get("grouping", DocX.c.NamespaceName)), value);
}
}
protected override XElement CreateChartXml()
{
return XElement.Parse(
@"<c:lineChart xmlns:c=""http://schemas.openxmlformats.org/drawingml/2006/chart"">
<c:grouping val=""standard""/>
</c:lineChart>");
}
}
/// <summary>
/// Specifies the kind of grouping for a column, line, or area chart.
/// 21.2.2.76 grouping (Grouping)
/// </summary>
public enum Grouping
{
[XmlName("percentStacked")]
PercentStacked,
[XmlName("stacked")]
Stacked,
[XmlName("standard")]
Standard
}
}

+ 0
- 22
DocX/Charts/PieChart.cs View File

@@ -1,22 +0,0 @@
using System;
using System.Xml.Linq;
namespace Novacode
{
/// <summary>
/// This element contains the 2-D pie series for this chart.
/// 21.2.2.141 pieChart (Pie Charts)
/// </summary>
public class PieChart : Chart
{
public override Boolean IsAxisExist { get { return false; } }
public override Int16 MaxSeriesCount { get { return 1; } }
protected override XElement CreateChartXml()
{
return XElement.Parse(
@"<c:pieChart xmlns:c=""http://schemas.openxmlformats.org/drawingml/2006/chart"">
</c:pieChart>");
}
}
}

+ 0
- 85
DocX/Charts/XElementHelpers.cs View File

@@ -1,85 +0,0 @@
using System;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
namespace Novacode
{
internal static class XElementHelpers
{
/// <summary>
/// Get value from XElement and convert it to enum
/// </summary>
/// <typeparam name="T">Enum type</typeparam>
internal static T GetValueToEnum<T>(XElement element)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
String value = element.Attribute(XName.Get("val")).Value;
foreach (T e in Enum.GetValues(typeof(T)))
{
FieldInfo fi = typeof(T).GetField(e.ToString());
if (fi.GetCustomAttributes(typeof(XmlNameAttribute), false).Count() == 0)
throw new Exception(String.Format("Attribute 'XmlNameAttribute' is not assigned to {0} fields!", typeof(T).Name));
XmlNameAttribute a = (XmlNameAttribute)fi.GetCustomAttributes(typeof(XmlNameAttribute), false).First();
if (a.XmlName == value)
return e;
}
throw new ArgumentException("Invalid element value!");
}
/// <summary>
/// Convert value to xml string and set it into XElement
/// </summary>
/// <typeparam name="T">Enum type</typeparam>
internal static void SetValueFromEnum<T>(XElement element, T value)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
element.Attribute(XName.Get("val")).Value = GetXmlNameFromEnum<T>(value);
}
/// <summary>
/// Return xml string for this value
/// </summary>
/// <typeparam name="T">Enum type</typeparam>
internal static String GetXmlNameFromEnum<T>(T value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
FieldInfo fi = typeof(T).GetField(value.ToString());
if (fi.GetCustomAttributes(typeof(XmlNameAttribute), false).Count() == 0)
throw new Exception(String.Format("Attribute 'XmlNameAttribute' is not assigned to {0} fields!", typeof(T).Name));
XmlNameAttribute a = (XmlNameAttribute)fi.GetCustomAttributes(typeof(XmlNameAttribute), false).First();
return a.XmlName;
}
}
/// <summary>
/// This attribute applied to enum's fields for definition their's real xml names in DocX file.
/// </summary>
/// <example>
/// public enum MyEnum
/// {
/// [XmlName("one")] // This means, that xml element has 'val="one"'
/// ValueOne,
/// [XmlName("two")] // This means, that xml element has 'val="two"'
/// ValueTwo
/// }
/// </example>
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
internal sealed class XmlNameAttribute : Attribute
{
/// <summary>
/// Real xml name
/// </summary>
public String XmlName { get; private set; }
public XmlNameAttribute(String xmlName)
{
XmlName = xmlName;
}
}
}

+ 0
- 1048
DocX/Container.cs
File diff suppressed because it is too large
View File


+ 0
- 29
DocX/Content.cs View File

@@ -1,29 +0,0 @@
using System.Linq;
using System.Collections.Generic;
using System.Xml.Linq;

namespace Novacode
{
public class Content : InsertBeforeOrAfter
{

public string Name { get; set; }
public string Tag { get; set; }
public string Text { get; set; }
public List<Content> Sections { get; set; }
public ContainerType ParentContainer;


internal Content(DocX document, XElement xml, int startIndex)
: base(document, xml)
{
}

public void SetText(string newText)
{
Xml.Descendants(XName.Get("t", DocX.w.NamespaceName)).First().Value = newText;
}

}
}

+ 0
- 17
DocX/ContentCollection.cs View File

@@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;

namespace Novacode
{
public class ContentCollection : List<Content>
{
public Content this[string name]
{
get
{
return this.FirstOrDefault(content => string.Equals(content.Name, name, StringComparison.CurrentCultureIgnoreCase));
}
}
}
}

+ 0
- 107
DocX/CustomProperty.cs View File

@@ -1,107 +0,0 @@
using System;
namespace Novacode
{
public class CustomProperty
{
/// <summary>
/// The name of this CustomProperty.
/// </summary>
public string Name { get; }
/// <summary>
/// The value of this CustomProperty.
/// </summary>
public object Value { get; }
internal string Type { get; }
internal CustomProperty(string name, string type, string value)
{
object realValue;
switch (type)
{
case "lpwstr":
{
realValue = value;
break;
}
case "i4":
{
realValue = int.Parse(value, System.Globalization.CultureInfo.InvariantCulture);
break;
}
case "r8":
{
realValue = Double.Parse(value, System.Globalization.CultureInfo.InvariantCulture);
break;
}
case "filetime":
{
realValue = DateTime.Parse(value, System.Globalization.CultureInfo.InvariantCulture);
break;
}
case "bool":
{
realValue = bool.Parse(value);
break;
}
default: throw new Exception();
}
Name = name;
Type = type;
Value = realValue;
}
private CustomProperty(string name, string type, object value)
{
Name = name;
Type = type;
Value = value;
}
/// <summary>
/// Create a new CustomProperty to hold a string.
/// </summary>
/// <param name="name">The name of this CustomProperty.</param>
/// <param name="value">The value of this CustomProperty.</param>
public CustomProperty(string name, string value) : this(name, "lpwstr", value as object) { }
/// <summary>
/// Create a new CustomProperty to hold an int.
/// </summary>
/// <param name="name">The name of this CustomProperty.</param>
/// <param name="value">The value of this CustomProperty.</param>
public CustomProperty(string name, int value) : this(name, "i4", value) { }
/// <summary>
/// Create a new CustomProperty to hold a double.
/// </summary>
/// <param name="name">The name of this CustomProperty.</param>
/// <param name="value">The value of this CustomProperty.</param>
public CustomProperty(string name, double value) : this(name, "r8", value) { }
/// <summary>
/// Create a new CustomProperty to hold a DateTime.
/// </summary>
/// <param name="name">The name of this CustomProperty.</param>
/// <param name="value">The value of this CustomProperty.</param>
public CustomProperty(string name, DateTime value) : this(name, "filetime", value.ToUniversalTime()) { }
/// <summary>
/// Create a new CustomProperty to hold a bool.
/// </summary>
/// <param name="name">The name of this CustomProperty.</param>
/// <param name="value">The value of this CustomProperty.</param>
public CustomProperty(string name, bool value) : this(name, "bool", value) { }
}
}

+ 0
- 24
DocX/DocProperty.cs View File

@@ -1,24 +0,0 @@
using System.Xml.Linq;
using System.Text.RegularExpressions;
namespace Novacode
{
/// <summary>
/// Represents a field of type document property. This field displays the value stored in a custom property.
/// </summary>
public class DocProperty: DocXElement
{
internal Regex extractName = new Regex(@"DOCPROPERTY (?<name>.*) ");
/// <summary>
/// The custom property to display.
/// </summary>
public string Name { get; }
internal DocProperty(DocX document, XElement xml):base(document, xml)
{
string instr = Xml.Attribute(XName.Get("instr", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")).Value;
Name = extractName.Match(instr.Trim()).Groups["name"].Value;
}
}
}

+ 0
- 4598
DocX/DocX.cs
File diff suppressed because it is too large
View File


+ 0
- 10
DocX/DocX.csproj.vspscc View File

@@ -1,10 +0,0 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}

+ 0
- 8
DocX/DocumentTypes.cs View File

@@ -1,8 +0,0 @@
namespace Novacode
{
public enum DocumentTypes
{
Document,
Template
}
}

+ 0
- 59
DocX/ExtensionsHeadings.cs View File

@@ -1,59 +0,0 @@
using System;
using System.ComponentModel;
using System.Reflection;
namespace Novacode
{
public static class ExtensionsHeadings
{
public static Paragraph Heading(this Paragraph paragraph, HeadingType headingType)
{
string StyleName = headingType.EnumDescription();
paragraph.StyleName = StyleName;
return paragraph;
}
public static string EnumDescription(this Enum enumValue)
{
if (enumValue == null || enumValue.ToString() == "0")
{
return string.Empty;
}
FieldInfo enumInfo = enumValue.GetType().GetField(enumValue.ToString());
DescriptionAttribute[] enumAttributes = (DescriptionAttribute[])enumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (enumAttributes.Length > 0)
{
return enumAttributes[0].Description;
}
return enumValue.ToString();
}
/// <summary>
/// From: http://stackoverflow.com/questions/4108828/generic-extension-method-to-see-if-an-enum-contains-a-flag
/// Check to see if a flags enumeration has a specific flag set.
/// </summary>
/// <param name="variable">Flags enumeration to check</param>
/// <param name="value">Flag to check for</param>
/// <returns></returns>
public static bool HasFlag(this Enum variable, Enum value)
{
if (variable == null)
return false;
if (value == null)
throw new ArgumentNullException(nameof(value));
// Not as good as the .NET 4 version of this function, but should be good enough
if (!Enum.IsDefined(variable.GetType(), value))
{
throw new ArgumentException(string.Format(
"Enumeration type mismatch. The flag is of type '{0}', was expecting '{1}'.",
value.GetType(), variable.GetType()));
}
ulong num = Convert.ToUInt64(value);
return ((Convert.ToUInt64(variable) & num) == num);
}
}
}

+ 0
- 38
DocX/Font.cs View File

@@ -1,38 +0,0 @@
using System;

namespace Novacode
{
/// <summary>
/// Represents a font family
/// </summary>
public sealed class Font
{
/// <summary>
/// Initializes a new instance of <see cref="Font" />
/// </summary>
/// <param name="name">The name of the font family</param>
public Font(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));
}

Name = name;
}

/// <summary>
/// The name of the font family
/// </summary>
public string Name { get; private set; }

/// <summary>
/// Returns a string representation of an object
/// </summary>
/// <returns>The name of the font family</returns>
public override string ToString()
{
return Name;
}
}
}

+ 0
- 172
DocX/Footer.cs View File

@@ -1,172 +0,0 @@
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.IO.Packaging;
using System.Collections.ObjectModel;
namespace Novacode
{
public class Footer : Container, IParagraphContainer
{
public bool PageNumbers
{
get
{
return false;
}
set
{
XElement e = XElement.Parse
(@"<w:sdt xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
<w:sdtPr>
<w:id w:val='157571950' />
<w:docPartObj>
<w:docPartGallery w:val='Page Numbers (Top of Page)' />
<w:docPartUnique />
</w:docPartObj>
</w:sdtPr>
<w:sdtContent>
<w:p w:rsidR='008D2BFB' w:rsidRDefault='008D2BFB'>
<w:pPr>
<w:pStyle w:val='Header' />
<w:jc w:val='center' />
</w:pPr>
<w:fldSimple w:instr=' PAGE \* MERGEFORMAT'>
<w:r>
<w:rPr>
<w:noProof />
</w:rPr>
<w:t>1</w:t>
</w:r>
</w:fldSimple>
</w:p>
</w:sdtContent>
</w:sdt>"
);
Xml.AddFirst(e);
}
}
internal Footer(DocX document, XElement xml, PackagePart mainPart): base(document, xml)
{
this.mainPart = mainPart;
}
public override Paragraph InsertParagraph()
{
Paragraph p = base.InsertParagraph();
p.PackagePart = mainPart;
return p;
}
public override Paragraph InsertParagraph(int index, string text, bool trackChanges)
{
Paragraph p = base.InsertParagraph(index, text, trackChanges);
p.PackagePart = mainPart;
return p;
}
public override Paragraph InsertParagraph(Paragraph p)
{
p.PackagePart = mainPart;
return base.InsertParagraph(p);
}
public override Paragraph InsertParagraph(int index, Paragraph p)
{
p.PackagePart = mainPart;
return base.InsertParagraph(index, p);
}
public override Paragraph InsertParagraph(int index, string text, bool trackChanges, Formatting formatting)
{
Paragraph p = base.InsertParagraph(index, text, trackChanges, formatting);
p.PackagePart = mainPart;
return p;
}
public override Paragraph InsertParagraph(string text)
{
Paragraph p = base.InsertParagraph(text);
p.PackagePart = mainPart;
return p;
}
public override Paragraph InsertParagraph(string text, bool trackChanges)
{
Paragraph p = base.InsertParagraph(text, trackChanges);
p.PackagePart = mainPart;
return p;
}
public override Paragraph InsertParagraph(string text, bool trackChanges, Formatting formatting)
{
Paragraph p = base.InsertParagraph(text, trackChanges, formatting);
p.PackagePart = mainPart;
return p;
}
public override Paragraph InsertEquation(String equation)
{
Paragraph p = base.InsertEquation(equation);
p.PackagePart = mainPart;
return p;
}
public override ReadOnlyCollection<Paragraph> Paragraphs
{
get
{
ReadOnlyCollection<Paragraph> l = base.Paragraphs;
foreach (var paragraph in l)
{
paragraph.mainPart = mainPart;
}
return l;
}
}
public override List<Table> Tables
{
get
{
List<Table> l = base.Tables;
l.ForEach(x => x.mainPart = mainPart);
return l;
}
}
public new Table InsertTable(int rowCount, int columnCount)
{
if (rowCount < 1 || columnCount < 1)
throw new ArgumentOutOfRangeException("Row and Column count must be greater than zero.");
Table t = base.InsertTable(rowCount, columnCount);
t.mainPart = mainPart;
return t;
}
public new Table InsertTable(int index, Table t)
{
Table t2 = base.InsertTable(index, t);
t2.mainPart = mainPart;
return t2;
}
public new Table InsertTable(Table t)
{
t = base.InsertTable(t);
t.mainPart = mainPart;
return t;
}
public new Table InsertTable(int index, int rowCount, int columnCount)
{
if (rowCount < 1 || columnCount < 1)
throw new ArgumentOutOfRangeException("Row and Column count must be greater than zero.");
Table t = base.InsertTable(index, rowCount, columnCount);
t.mainPart = mainPart;
return t;
}
}
}

+ 0
- 14
DocX/Footers.cs View File

@@ -1,14 +0,0 @@
namespace Novacode
{
public class Footers
{
internal Footers()
{
}
public Footer odd;
public Footer even;
public Footer first;
}
}

+ 0
- 27
DocX/FormattedText.cs View File

@@ -1,27 +0,0 @@
using System;
namespace Novacode
{
public class FormattedText: IComparable
{
public FormattedText()
{
}
public int index;
public string text;
public Formatting formatting;
public int CompareTo(object obj)
{
FormattedText other = (FormattedText)obj;
FormattedText tf = this;
if (other.formatting == null || tf.formatting == null)
return -1;
return tf.formatting.CompareTo(other.formatting);
}
}
}

+ 0
- 548
DocX/Formatting.cs View File

@@ -1,548 +0,0 @@
using System;
using System.Linq;
using System.Xml.Linq;
using System.Drawing;
using System.Globalization;
namespace Novacode
{
/// <summary>
/// A text formatting.
/// </summary>
public class Formatting : IComparable
{
private XElement rPr;
private bool? hidden;
private bool? bold;
private bool? italic;
private StrikeThrough? strikethrough;
private Script? script;
private Highlight? highlight;
private double? size;
private Color? fontColor;
private Color? underlineColor;
private UnderlineStyle? underlineStyle;
private Misc? misc;
private CapsStyle? capsStyle;
private Font fontFamily;
private int? percentageScale;
private int? kerning;
private int? position;
private double? spacing;
private CultureInfo language;
/// <summary>
/// A text formatting.
/// </summary>
public Formatting()
{
capsStyle = Novacode.CapsStyle.none;
strikethrough = Novacode.StrikeThrough.none;
script = Novacode.Script.none;
highlight = Novacode.Highlight.none;
underlineStyle = Novacode.UnderlineStyle.none;
misc = Novacode.Misc.none;
// Use current culture by default
language = CultureInfo.CurrentCulture;
rPr = new XElement(XName.Get("rPr", DocX.w.NamespaceName));
}
/// <summary>
/// Text language
/// </summary>
public CultureInfo Language
{
get
{
return language;
}
set
{
language = value;
}
}
/// <summary>
/// Returns a new identical instance of Formatting.
/// </summary>
/// <returns></returns>
public Formatting Clone()
{
Formatting newf = new Formatting();
newf.Bold = bold;
newf.CapsStyle = capsStyle;
newf.FontColor = fontColor;
newf.FontFamily = fontFamily;
newf.Hidden = hidden;
newf.Highlight = highlight;
newf.Italic = italic;
if (kerning.HasValue) { newf.Kerning = kerning; }
newf.Language = language;
newf.Misc = misc;
if (percentageScale.HasValue) { newf.PercentageScale = percentageScale; }
if (position.HasValue) { newf.Position = position; }
newf.Script = script;
if (size.HasValue) { newf.Size = size; }
if (spacing.HasValue) { newf.Spacing = spacing; }
newf.StrikeThrough = strikethrough;
newf.UnderlineColor = underlineColor;
newf.UnderlineStyle = underlineStyle;
return newf;
}
public static Formatting Parse(XElement rPr)
{
Formatting formatting = new Formatting();
// Build up the Formatting object.
foreach (XElement option in rPr.Elements())
{
switch (option.Name.LocalName)
{
case "lang":
formatting.Language = new CultureInfo(
option.GetAttribute(XName.Get("val", DocX.w.NamespaceName), null) ??
option.GetAttribute(XName.Get("eastAsia", DocX.w.NamespaceName), null) ??
option.GetAttribute(XName.Get("bidi", DocX.w.NamespaceName)));
break;
case "spacing":
formatting.Spacing = Double.Parse(
option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 20.0;
break;
case "position":
formatting.Position = Int32.Parse(
option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 2;
break;
case "kern":
formatting.Position = Int32.Parse(
option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 2;
break;
case "w":
formatting.PercentageScale = Int32.Parse(
option.GetAttribute(XName.Get("val", DocX.w.NamespaceName)));
break;
// <w:sz w:val="20"/><w:szCs w:val="20"/>
case "sz":
formatting.Size = Int32.Parse(
option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 2;
break;
case "rFonts":
formatting.FontFamily =
new Font(
option.GetAttribute(XName.Get("cs", DocX.w.NamespaceName), null) ??
option.GetAttribute(XName.Get("ascii", DocX.w.NamespaceName), null) ??
option.GetAttribute(XName.Get("hAnsi", DocX.w.NamespaceName), null) ??
option.GetAttribute(XName.Get("eastAsia", DocX.w.NamespaceName)));
break;
case "color" :
try
{
string color = option.GetAttribute(XName.Get("val", DocX.w.NamespaceName));
formatting.FontColor = System.Drawing.ColorTranslator.FromHtml(string.Format("#{0}", color));
}
catch { }
break;
case "vanish": formatting.hidden = true; break;
case "b": formatting.Bold = true; break;
case "i": formatting.Italic = true; break;
case "u": formatting.UnderlineStyle = HelperFunctions.GetUnderlineStyle(option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))); break;
case "vertAlign":
var script = option.GetAttribute(XName.Get("val", DocX.w.NamespaceName), null);
formatting.Script = (Script)Enum.Parse(typeof(Script), script);
break;
default: break;
}
}
return formatting;
}
internal XElement Xml
{
get
{
rPr = new XElement(XName.Get("rPr", DocX.w.NamespaceName));
if (language != null)
rPr.Add(new XElement(XName.Get("lang", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), language.Name)));
if(spacing.HasValue)
rPr.Add(new XElement(XName.Get("spacing", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), spacing.Value * 20)));
if(position.HasValue)
rPr.Add(new XElement(XName.Get("position", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), position.Value * 2)));
if (kerning.HasValue)
rPr.Add(new XElement(XName.Get("kern", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), kerning.Value * 2)));
if (percentageScale.HasValue)
rPr.Add(new XElement(XName.Get("w", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), percentageScale)));
if (fontFamily != null)
{
rPr.Add
(
new XElement
(
XName.Get("rFonts", DocX.w.NamespaceName),
new XAttribute(XName.Get("ascii", DocX.w.NamespaceName), fontFamily.Name),
new XAttribute(XName.Get("hAnsi", DocX.w.NamespaceName), fontFamily.Name), // Added by Maurits Elbers to support non-standard characters. See http://docx.codeplex.com/Thread/View.aspx?ThreadId=70097&ANCHOR#Post453865
new XAttribute(XName.Get("cs", DocX.w.NamespaceName), fontFamily.Name), // Added by Maurits Elbers to support non-standard characters. See http://docx.codeplex.com/Thread/View.aspx?ThreadId=70097&ANCHOR#Post453865
new XAttribute(XName.Get("eastAsia", DocX.w.NamespaceName), fontFamily.Name) // DOCX in china #57
)
);
}
if (hidden.HasValue && hidden.Value)
rPr.Add(new XElement(XName.Get("vanish", DocX.w.NamespaceName)));
if (bold.HasValue && bold.Value)
rPr.Add(new XElement(XName.Get("b", DocX.w.NamespaceName)));
if (italic.HasValue && italic.Value)
rPr.Add(new XElement(XName.Get("i", DocX.w.NamespaceName)));
if (underlineStyle.HasValue)
{
switch (underlineStyle)
{
case Novacode.UnderlineStyle.none:
break;
case Novacode.UnderlineStyle.singleLine:
rPr.Add(new XElement(XName.Get("u", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "single")));
break;
case Novacode.UnderlineStyle.doubleLine:
rPr.Add(new XElement(XName.Get("u", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "double")));
break;
default:
rPr.Add(new XElement(XName.Get("u", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), underlineStyle.ToString())));
break;
}
}
if(underlineColor.HasValue)
{
// If an underlineColor has been set but no underlineStyle has been set
if (underlineStyle == Novacode.UnderlineStyle.none)
{
// Set the underlineStyle to the default
underlineStyle = Novacode.UnderlineStyle.singleLine;
rPr.Add(new XElement(XName.Get("u", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "single")));
}
rPr.Element(XName.Get("u", DocX.w.NamespaceName)).Add(new XAttribute(XName.Get("color", DocX.w.NamespaceName), underlineColor.Value.ToHex()));
}
if (strikethrough.HasValue)
{
switch (strikethrough)
{
case Novacode.StrikeThrough.none:
break;
case Novacode.StrikeThrough.strike:
rPr.Add(new XElement(XName.Get("strike", DocX.w.NamespaceName)));
break;
case Novacode.StrikeThrough.doubleStrike:
rPr.Add(new XElement(XName.Get("dstrike", DocX.w.NamespaceName)));
break;
default:
break;
}
}
if (script.HasValue)
{
switch (script)
{
case Novacode.Script.none:
break;
default:
rPr.Add(new XElement(XName.Get("vertAlign", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), script.ToString())));
break;
}
}
if (size.HasValue)
{
rPr.Add(new XElement(XName.Get("sz", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), (size * 2).ToString())));
rPr.Add(new XElement(XName.Get("szCs", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), (size * 2).ToString())));
}
if(fontColor.HasValue)
rPr.Add(new XElement(XName.Get("color", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), fontColor.Value.ToHex())));
if (highlight.HasValue)
{
switch (highlight)
{
case Novacode.Highlight.none:
break;
default:
rPr.Add(new XElement(XName.Get("highlight", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), highlight.ToString())));
break;
}
}
if (capsStyle.HasValue)
{
switch (capsStyle)
{
case Novacode.CapsStyle.none:
break;
default:
rPr.Add(new XElement(XName.Get(capsStyle.ToString(), DocX.w.NamespaceName)));
break;
}
}
if (misc.HasValue)
{
switch (misc)
{
case Novacode.Misc.none:
break;
case Novacode.Misc.outlineShadow:
rPr.Add(new XElement(XName.Get("outline", DocX.w.NamespaceName)));
rPr.Add(new XElement(XName.Get("shadow", DocX.w.NamespaceName)));
break;
case Novacode.Misc.engrave:
rPr.Add(new XElement(XName.Get("imprint", DocX.w.NamespaceName)));
break;
default:
rPr.Add(new XElement(XName.Get(misc.ToString(), DocX.w.NamespaceName)));
break;
}
}
return rPr;
}
}
/// <summary>
/// This formatting will apply Bold.
/// </summary>
public bool? Bold { get { return bold; } set { bold = value;} }
/// <summary>
/// This formatting will apply Italic.
/// </summary>
public bool? Italic { get { return italic; } set { italic = value; } }
/// <summary>
/// This formatting will apply StrickThrough.
/// </summary>
public StrikeThrough? StrikeThrough { get { return strikethrough; } set { strikethrough = value; } }
/// <summary>
/// The script that this formatting should be, normal, superscript or subscript.
/// </summary>
public Script? Script { get { return script; } set { script = value; } }
/// <summary>
/// The Size of this text, must be between 0 and 1638.
/// </summary>
public double? Size
{
get { return size; }
set
{
double? temp = value * 2;
if (temp - (int)temp == 0)
{
if(value > 0 && value < 1639)
size = value;
else
throw new ArgumentException("Size", "Value must be in the range 0 - 1638");
}
else
throw new ArgumentException("Size", "Value must be either a whole or half number, examples: 32, 32.5");
}
}
/// <summary>
/// Percentage scale must be one of the following values 200, 150, 100, 90, 80, 66, 50 or 33.
/// </summary>
public int? PercentageScale
{
get { return percentageScale; }
set
{
if ((new int?[] { 200, 150, 100, 90, 80, 66, 50, 33 }).Contains(value))
percentageScale = value;
else
throw new ArgumentOutOfRangeException("PercentageScale", "Value must be one of the following: 200, 150, 100, 90, 80, 66, 50 or 33");
}
}
/// <summary>
/// The Kerning to apply to this text must be one of the following values 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72.
/// </summary>
public int? Kerning
{
get { return kerning; }
set
{
if(new int?[] {8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72}.Contains(value))
kerning = value;
else
throw new ArgumentOutOfRangeException("Kerning", "Value must be one of the following: 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48 or 72");
}
}
/// <summary>
/// Text position must be in the range (-1585 - 1585).
/// </summary>
public int? Position
{
get { return position; }
set
{
if (value > -1585 && value < 1585)
position = value;
else
throw new ArgumentOutOfRangeException("Position", "Value must be in the range -1585 - 1585");
}
}
/// <summary>
/// Text spacing must be in the range (-1585 - 1585).
/// </summary>
public double? Spacing
{
get { return spacing; }
set
{
double? temp = value * 20;
if (temp - (int)temp == 0)
{
if (value > -1585 && value < 1585)
spacing = value;
else
throw new ArgumentException("Spacing", "Value must be in the range: -1584 - 1584");
}
else
throw new ArgumentException("Spacing", "Value must be either a whole or acurate to one decimal, examples: 32, 32.1, 32.2, 32.9");
}
}
/// <summary>
/// The colour of the text.
/// </summary>
public Color? FontColor { get { return fontColor; } set { fontColor = value; } }
/// <summary>
/// Highlight colour.
/// </summary>
public Highlight? Highlight { get { return highlight; } set { highlight = value; } }
/// <summary>
/// The Underline style that this formatting applies.
/// </summary>
public UnderlineStyle? UnderlineStyle { get { return underlineStyle; } set { underlineStyle = value; } }
/// <summary>
/// The underline colour.
/// </summary>
public Color? UnderlineColor { get { return underlineColor; } set { underlineColor = value; } }
/// <summary>
/// Misc settings.
/// </summary>
public Misc? Misc { get { return misc; } set { misc = value; } }
/// <summary>
/// Is this text hidden or visible.
/// </summary>
public bool? Hidden { get { return hidden; } set { hidden = value; } }
/// <summary>
/// Capitalization style.
/// </summary>
public CapsStyle? CapsStyle { get { return capsStyle; } set { capsStyle = value; } }
/// <summary>
/// The font family of this formatting.
/// </summary>
/// <!--
/// Bug found and fixed by krugs525 on August 12 2009.
/// Use TFS compare to see exact code change.
/// -->
public Font FontFamily { get { return fontFamily; } set { fontFamily = value; } }
public int CompareTo(object obj)
{
Formatting other = (Formatting)obj;
if(other.hidden != this.hidden)
return -1;
if(other.bold != this.bold)
return -1;
if(other.italic != this.italic)
return -1;
if(other.strikethrough != this.strikethrough)
return -1;
if(other.script != this.script)
return -1;
if(other.highlight != this.highlight)
return -1;
if(other.size != this.size)
return -1;
if(other.fontColor != this.fontColor)
return -1;
if(other.underlineColor != this.underlineColor)
return -1;
if(other.underlineStyle != this.underlineStyle)
return -1;
if(other.misc != this.misc)
return -1;
if(other.capsStyle != this.capsStyle)
return -1;
if(other.fontFamily != this.fontFamily)
return -1;
if(other.percentageScale != this.percentageScale)
return -1;
if(other.kerning != this.kerning)
return -1;
if(other.position != this.position)
return -1;
if(other.spacing != this.spacing)
return -1;
if (!other.language.Equals(this.language))
return -1;
return 0;
}
}
}

+ 0
- 197
DocX/Header.cs View File

@@ -1,197 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.IO.Packaging;
using System.Collections.ObjectModel;
namespace Novacode
{
public class Header : Container, IParagraphContainer
{
public bool PageNumbers
{
get
{
return false;
}
set
{
XElement e = XElement.Parse
(@"<w:sdt xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
<w:sdtPr>
<w:id w:val='157571950' />
<w:docPartObj>
<w:docPartGallery w:val='Page Numbers (Top of Page)' />
<w:docPartUnique />
</w:docPartObj>
</w:sdtPr>
<w:sdtContent>
<w:p w:rsidR='008D2BFB' w:rsidRDefault='008D2BFB'>
<w:pPr>
<w:pStyle w:val='Header' />
<w:jc w:val='center' />
</w:pPr>
<w:fldSimple w:instr=' PAGE \* MERGEFORMAT'>
<w:r>
<w:rPr>
<w:noProof />
</w:rPr>
<w:t>1</w:t>
</w:r>
</w:fldSimple>
</w:p>
</w:sdtContent>
</w:sdt>"
);
Xml.AddFirst(e);
PageNumberParagraph = new Paragraph(Document, e.Descendants(XName.Get("p", DocX.w.NamespaceName)).SingleOrDefault(), 0);
}
}
public Paragraph PageNumberParagraph;
internal Header(DocX document, XElement xml, PackagePart mainPart):base(document, xml)
{
this.mainPart = mainPart;
}
public override Paragraph InsertParagraph()
{
Paragraph p = base.InsertParagraph();
p.PackagePart = mainPart;
return p;
}
public override Paragraph InsertParagraph(int index, string text, bool trackChanges)
{
Paragraph p = base.InsertParagraph(index, text, trackChanges);
p.PackagePart = mainPart;
return p;
}
public override Paragraph InsertParagraph(Paragraph p)
{
p.PackagePart = mainPart;
return base.InsertParagraph(p);
}
public override Paragraph InsertParagraph(int index, Paragraph p)
{
p.PackagePart = mainPart;
return base.InsertParagraph(index, p);
}
public override Paragraph InsertParagraph(int index, string text, bool trackChanges, Formatting formatting)
{
Paragraph p = base.InsertParagraph(index, text, trackChanges, formatting);
p.PackagePart = mainPart;
return p;
}
public override Paragraph InsertParagraph(string text)
{
Paragraph p = base.InsertParagraph(text);
p.PackagePart = mainPart;
return p;
}
public override Paragraph InsertParagraph(string text, bool trackChanges)
{
Paragraph p = base.InsertParagraph(text, trackChanges);
p.PackagePart = mainPart;
return p;
}
public override Paragraph InsertParagraph(string text, bool trackChanges, Formatting formatting)
{
Paragraph p = base.InsertParagraph(text, trackChanges, formatting);
p.PackagePart = mainPart;
return p;
}
public override Paragraph InsertEquation(String equation)
{
Paragraph p = base.InsertEquation(equation);
p.PackagePart = mainPart;
return p;
}
public override ReadOnlyCollection<Paragraph> Paragraphs
{
get
{
ReadOnlyCollection<Paragraph> l = base.Paragraphs;
foreach (var paragraph in l)
{
paragraph.mainPart = mainPart;
}
return l;
}
}
public override List<Table> Tables
{
get
{
List<Table> l = base.Tables;
l.ForEach(x => x.mainPart = mainPart);
return l;
}
}
public List<Image> Images
{
get
{
PackageRelationshipCollection imageRelationships = mainPart.GetRelationshipsByType(DocX.relationshipImage);
if (imageRelationships.Count() > 0)
{
return
(
from i in imageRelationships
select new Image(Document, i)
).ToList();
}
return new List<Image>();
}
}
public new Table InsertTable(int rowCount, int columnCount)
{
if (rowCount < 1 || columnCount < 1)
throw new ArgumentOutOfRangeException("Row and Column count must be greater than zero.");
Table t = base.InsertTable(rowCount, columnCount);
t.mainPart = mainPart;
return t;
}
public new Table InsertTable(int index, Table t)
{
Table t2 = base.InsertTable(index, t);
t2.mainPart = mainPart;
return t2;
}
public new Table InsertTable(Table t)
{
t = base.InsertTable(t);
t.mainPart = mainPart;
return t;
}
public new Table InsertTable(int index, int rowCount, int columnCount)
{
if (rowCount < 1 || columnCount < 1)
throw new ArgumentOutOfRangeException("Row and Column count must be greater than zero.");
Table t = base.InsertTable(index, rowCount, columnCount);
t.mainPart = mainPart;
return t;
}
}
}

+ 0
- 13
DocX/Headers.cs View File

@@ -1,13 +0,0 @@
namespace Novacode
{
public class Headers
{
internal Headers()
{
}
public Header odd;
public Header even;
public Header first;
}
}

BIN
DocX/Help/DocX v1.0.0.10 - Documentation.chm View File


BIN
DocX/Help/Read Me.docx View File


+ 0
- 773
DocX/HelperFunctions.cs View File

@@ -1,773 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.IO.Packaging;
using System.Linq;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using System.Xml.Linq;
namespace Novacode
{
internal static class HelperFunctions
{
public const string DOCUMENT_DOCUMENTTYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
public const string TEMPLATE_DOCUMENTTYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml";
public const string MACRO_DOCUMENTTYPE = "application/vnd.ms-word.document.macroEnabled.main+xml";
/// <summary>
/// List of restricted character in xml: [#x1-#x8] | [#xB-#xC] | [#xE-#x1F] | [#x7F-#x84] | [#x86-#x9F]
/// See: https://www.w3.org/TR/xml11/#sec-xml11
/// </summary>
public static readonly char[] RestrictedXmlChar = new char[] {
'\x1','\x2','\x3','\x4','\x5','\x6','\x7','\x8','\xb','\xc','\xe','\xf',
'\x10','\x11','\x12','\x13','\x14','\x15','\x16','\x17','\x18','\x19','\x1a','\x1b','\x1c','\x1e','\x1f',
'\x7f','\x80','\x81','\x82','\x83','\x84','\x86','\x87','\x88','\x89','\x8a','\x8b','\x8c','\x8d','\x8e','\x8f',
'\x90','\x91','\x92','\x93','\x94','\x95','\x96','\x97','\x98','\x99','\x9a','\x9b','\x9c','\x9d','\x9e','\x9f'
};
public static bool IsNullOrWhiteSpace(this string value)
{
if (value == null) return true;
return string.IsNullOrEmpty(value.Trim());
}
/// <summary>
/// Checks whether 'toCheck' has all children that 'desired' has and values of 'val' attributes are the same
/// </summary>
/// <param name="desired"></param>
/// <param name="toCheck"></param>
/// <param name="fo">Matching options whether check if desired attributes are inder a, or a has exactly and only these attributes as b has.</param>
/// <returns></returns>
internal static bool ContainsEveryChildOf(XElement desired, XElement toCheck, MatchFormattingOptions fo)
{
foreach (XElement e in desired.Elements())
{
// If a formatting property has the same name and 'val' attribute's value, its considered to be equivalent.
if (!toCheck.Elements(e.Name).Where(bElement => bElement.GetAttribute(XName.Get("val", DocX.w.NamespaceName)) == e.GetAttribute(XName.Get("val", DocX.w.NamespaceName))).Any())
return false;
}
// If the formatting has to be exact, no additionaly formatting must exist.
if (fo == MatchFormattingOptions.ExactMatch)
return desired.Elements().Count() == toCheck.Elements().Count();
return true;
}
internal static void CreateRelsPackagePart(DocX Document, Uri uri)
{
PackagePart pp = Document.package.CreatePart(uri, DocX.contentTypeApplicationRelationShipXml, CompressionOption.Maximum);
using (TextWriter tw = new StreamWriter(new PackagePartStream(pp.GetStream())))
{
XDocument d = new XDocument
(
new XDeclaration("1.0", "UTF-8", "yes"),
new XElement(XName.Get("Relationships", DocX.rel.NamespaceName))
);
var root = d.Root;
d.Save(tw);
}
}
internal static int GetSize(XElement Xml)
{
switch (Xml.Name.LocalName)
{
case "tab":
return 1;
case "br":
return 1;
case "t":
goto case "delText";
case "delText":
return Xml.Value.Length;
case "tr":
goto case "br";
case "tc":
goto case "br";
default:
return 0;
}
}
internal static string GetText(XElement e)
{
StringBuilder sb = new StringBuilder();
GetTextRecursive(e, ref sb);
return sb.ToString();
}
internal static void GetTextRecursive(XElement Xml, ref StringBuilder sb)
{
sb.Append(ToText(Xml));
if (Xml.HasElements)
foreach (XElement e in Xml.Elements())
GetTextRecursive(e, ref sb);
}
internal static List<FormattedText> GetFormattedText(XElement e)
{
List<FormattedText> alist = new List<FormattedText>();
GetFormattedTextRecursive(e, ref alist);
return alist;
}
internal static void GetFormattedTextRecursive(XElement Xml, ref List<FormattedText> alist)
{
FormattedText ft = ToFormattedText(Xml);
FormattedText last = null;
if (ft != null)
{
if (alist.Count() > 0)
last = alist.Last();
if (last != null && last.CompareTo(ft) == 0)
{
// Update text of last entry.
last.text += ft.text;
}
else
{
if (last != null)
ft.index = last.index + last.text.Length;
alist.Add(ft);
}
}
if (Xml.HasElements)
foreach (XElement e in Xml.Elements())
GetFormattedTextRecursive(e, ref alist);
}
internal static FormattedText ToFormattedText(XElement e)
{
// The text representation of e.
String text = ToText(e);
if (text == String.Empty)
return null;
// e is a w:t element, it must exist inside a w:r element or a w:tabs, lets climb until we find it.
while (!e.Name.Equals(XName.Get("r", DocX.w.NamespaceName)) &&
!e.Name.Equals(XName.Get("tabs", DocX.w.NamespaceName)))
e = e.Parent;
// e is a w:r element, lets find the rPr element.
XElement rPr = e.Element(XName.Get("rPr", DocX.w.NamespaceName));
FormattedText ft = new FormattedText();
ft.text = text;
ft.index = 0;
ft.formatting = null;
// Return text with formatting.
if (rPr != null)
ft.formatting = Formatting.Parse(rPr);
return ft;
}
internal static string ToText(XElement e)
{
switch (e.Name.LocalName)
{
case "tab":
return "\t";
case "br":
return "\n";
case "t":
goto case "delText";
case "delText":
{
if (e.Parent != null && e.Parent.Name.LocalName == "r")
{
XElement run = e.Parent;
var rPr = run.Elements().FirstOrDefault(a => a.Name.LocalName == "rPr");
if (rPr != null)
{
var caps = rPr.Elements().FirstOrDefault(a => a.Name.LocalName == "caps");
if (caps != null)
return e.Value.ToUpper();
}
}
return e.Value;
}
case "tr":
goto case "br";
case "tc":
goto case "tab";
default: return "";
}
}
internal static XElement CloneElement(XElement element)
{
return new XElement
(
element.Name,
element.Attributes(),
element.Nodes().Select
(
n =>
{
XElement e = n as XElement;
if (e != null)
return CloneElement(e);
return n;
}
)
);
}
internal static PackagePart GetMainDocumentPart(Package package)
{
return package.GetParts().Single(p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
p.ContentType.Equals(MACRO_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase));
}
internal static PackagePart CreateOrGetSettingsPart(Package package)
{
PackagePart settingsPart;
Uri settingsUri = new Uri("/word/settings.xml", UriKind.Relative);
if (!package.PartExists(settingsUri))
{
settingsPart = package.CreatePart(settingsUri, "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml", CompressionOption.Maximum);
PackagePart mainDocumentPart = GetMainDocumentPart(package);
mainDocumentPart.CreateRelationship(settingsUri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings");
XDocument settings = XDocument.Parse
(@"<?xml version='1.0' encoding='utf-8' standalone='yes'?>
<w:settings xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:r='http://schemas.openxmlformats.org/officeDocument/2006/relationships' xmlns:m='http://schemas.openxmlformats.org/officeDocument/2006/math' xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w10='urn:schemas-microsoft-com:office:word' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:sl='http://schemas.openxmlformats.org/schemaLibrary/2006/main'>
<w:zoom w:percent='100' />
<w:defaultTabStop w:val='720' />
<w:characterSpacingControl w:val='doNotCompress' />
<w:compat />
<w:rsids>
<w:rsidRoot w:val='00217F62' />
<w:rsid w:val='001915A3' />
<w:rsid w:val='00217F62' />
<w:rsid w:val='00A906D8' />
<w:rsid w:val='00AB5A74' />
<w:rsid w:val='00F071AE' />
</w:rsids>
<m:mathPr>
<m:mathFont m:val='Cambria Math' />
<m:brkBin m:val='before' />
<m:brkBinSub m:val='--' />
<m:smallFrac m:val='off' />
<m:dispDef />
<m:lMargin m:val='0' />
<m:rMargin m:val='0' />
<m:defJc m:val='centerGroup' />
<m:wrapIndent m:val='1440' />
<m:intLim m:val='subSup' />
<m:naryLim m:val='undOvr' />
</m:mathPr>
<w:themeFontLang w:val='en-IE' w:bidi='ar-SA' />
<w:clrSchemeMapping w:bg1='light1' w:t1='dark1' w:bg2='light2' w:t2='dark2' w:accent1='accent1' w:accent2='accent2' w:accent3='accent3' w:accent4='accent4' w:accent5='accent5' w:accent6='accent6' w:hyperlink='hyperlink' w:followedHyperlink='followedHyperlink' />
<w:shapeDefaults>
<o:shapedefaults v:ext='edit' spidmax='2050' />
<o:shapelayout v:ext='edit'>
<o:idmap v:ext='edit' data='1' />
</o:shapelayout>
</w:shapeDefaults>
<w:decimalSymbol w:val='.' />
<w:listSeparator w:val=',' />
</w:settings>"
);
XElement themeFontLang = settings.Root.Element(XName.Get("themeFontLang", DocX.w.NamespaceName));
themeFontLang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture);
// Save the settings document.
using (TextWriter tw = new StreamWriter(new PackagePartStream(settingsPart.GetStream())))
settings.Save(tw);
}
else
settingsPart = package.GetPart(settingsUri);
return settingsPart;
}
internal static void CreateCorePropertiesPart(DocX document)
{
PackagePart corePropertiesPart = document.package.CreatePart(new Uri("/docProps/core.xml", UriKind.Relative), "application/vnd.openxmlformats-package.core-properties+xml", CompressionOption.Maximum);
XDocument corePropDoc = XDocument.Parse(@"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<cp:coreProperties xmlns:cp='http://schemas.openxmlformats.org/package/2006/metadata/core-properties' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:dcterms='http://purl.org/dc/terms/' xmlns:dcmitype='http://purl.org/dc/dcmitype/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
<dc:title></dc:title>
<dc:subject></dc:subject>
<dc:creator></dc:creator>
<cp:keywords></cp:keywords>
<dc:description></dc:description>
<cp:lastModifiedBy></cp:lastModifiedBy>
<cp:revision>1</cp:revision>
<dcterms:created xsi:type='dcterms:W3CDTF'>"+ DateTime.UtcNow.ToString("s") + "Z" + @"</dcterms:created>
<dcterms:modified xsi:type='dcterms:W3CDTF'>" + DateTime.UtcNow.ToString("s") + "Z" + @"</dcterms:modified>
</cp:coreProperties>");
using (TextWriter tw = new StreamWriter(new PackagePartStream(corePropertiesPart.GetStream(FileMode.Create, FileAccess.Write))))
corePropDoc.Save(tw, SaveOptions.None);
document.package.CreateRelationship(corePropertiesPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties");
}
internal static void CreateCustomPropertiesPart(DocX document)
{
PackagePart customPropertiesPart = document.package.CreatePart(new Uri("/docProps/custom.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.custom-properties+xml", CompressionOption.Maximum);
XDocument customPropDoc = new XDocument
(
new XDeclaration("1.0", "UTF-8", "yes"),
new XElement
(
XName.Get("Properties", DocX.customPropertiesSchema.NamespaceName),
new XAttribute(XNamespace.Xmlns + "vt", DocX.customVTypesSchema)
)
);
using (TextWriter tw = new StreamWriter(new PackagePartStream(customPropertiesPart.GetStream(FileMode.Create, FileAccess.Write))))
customPropDoc.Save(tw, SaveOptions.None);
document.package.CreateRelationship(customPropertiesPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties");
}
internal static XDocument DecompressXMLResource(string manifest_resource_name)
{
// XDocument to load the compressed Xml resource into.
XDocument document;
// Get a reference to the executing assembly.
Assembly assembly = Assembly.GetExecutingAssembly();
// Open a Stream to the embedded resource.
Stream stream = assembly.GetManifestResourceStream(manifest_resource_name);
// Decompress the embedded resource.
using (GZipStream zip = new GZipStream(stream, CompressionMode.Decompress))
{
// Load this decompressed embedded resource into an XDocument using a TextReader.
using (TextReader sr = new StreamReader(zip))
{
document = XDocument.Load(sr);
}
}
// Return the decompressed Xml as an XDocument.
return document;
}
/// <summary>
/// If this document does not contain a /word/numbering.xml add the default one generated by Microsoft Word
/// when the default bullet, numbered and multilevel lists are added to a blank document
/// </summary>
/// <param name="package"></param>
/// <returns></returns>
internal static XDocument AddDefaultNumberingXml(Package package)
{
XDocument numberingDoc;
// Create the main document part for this package
PackagePart wordNumbering = package.CreatePart(new Uri("/word/numbering.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml", CompressionOption.Maximum);
numberingDoc = DecompressXMLResource("Novacode.Resources.numbering.xml.gz");
// Save /word/numbering.xml
using (TextWriter tw = new StreamWriter(new PackagePartStream(wordNumbering.GetStream(FileMode.Create, FileAccess.Write))))
numberingDoc.Save(tw, SaveOptions.None);
PackagePart mainDocumentPart = GetMainDocumentPart(package);
mainDocumentPart.CreateRelationship(wordNumbering.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering");
return numberingDoc;
}
/// <summary>
/// If this document does not contain a /word/styles.xml add the default one generated by Microsoft Word.
/// </summary>
/// <param name="package"></param>
/// <returns></returns>
internal static XDocument AddDefaultStylesXml(Package package)
{
XDocument stylesDoc;
// Create the main document part for this package
PackagePart word_styles = package.CreatePart(new Uri("/word/styles.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", CompressionOption.Maximum);
stylesDoc = HelperFunctions.DecompressXMLResource("Novacode.Resources.default_styles.xml.gz");
XElement lang = stylesDoc.Root.Element(XName.Get("docDefaults", DocX.w.NamespaceName)).Element(XName.Get("rPrDefault", DocX.w.NamespaceName)).Element(XName.Get("rPr", DocX.w.NamespaceName)).Element(XName.Get("lang", DocX.w.NamespaceName));
lang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture);
// Save /word/styles.xml
using (TextWriter tw = new StreamWriter(new PackagePartStream(word_styles.GetStream(FileMode.Create, FileAccess.Write))))
stylesDoc.Save(tw, SaveOptions.None);
PackagePart mainDocumentPart = GetMainDocumentPart(package);
mainDocumentPart.CreateRelationship(word_styles.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles");
return stylesDoc;
}
internal static XElement CreateEdit(EditType t, DateTime edit_time, object content)
{
if (t == EditType.del)
{
foreach (object o in (IEnumerable<XElement>)content)
{
if (o is XElement)
{
XElement e = (o as XElement);
IEnumerable<XElement> ts = e.DescendantsAndSelf(XName.Get("t", DocX.w.NamespaceName));
for (int i = 0; i < ts.Count(); i++)
{
XElement text = ts.ElementAt(i);
text.ReplaceWith(new XElement(DocX.w + "delText", text.Attributes(), text.Value));
}
}
}
}
return
(
new XElement(DocX.w + t.ToString(),
new XAttribute(DocX.w + "id", 0),
new XAttribute(DocX.w + "author", WindowsIdentity.GetCurrent().Name),
new XAttribute(DocX.w + "date", edit_time),
content)
);
}
internal static XElement CreateTable(int rowCount, int columnCount)
{
int[] columnWidths = new int[columnCount];
for (int i = 0; i < columnCount; i++)
{
columnWidths[i] = 2310;
}
return CreateTable(rowCount, columnWidths);
}
internal static XElement CreateTable(int rowCount, int[] columnWidths)
{
XElement newTable =
new XElement
(
XName.Get("tbl", DocX.w.NamespaceName),
new XElement
(
XName.Get("tblPr", DocX.w.NamespaceName),
new XElement(XName.Get("tblStyle", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "TableGrid")),
new XElement(XName.Get("tblW", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), "5000"), new XAttribute(XName.Get("type", DocX.w.NamespaceName), "auto")),
new XElement(XName.Get("tblLook", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "04A0"))
)
);
/*XElement tableGrid = new XElement(XName.Get("tblGrid", DocX.w.NamespaceName));
for (int i = 0; i < columnWidths.Length; i++)
tableGrid.Add(new XElement(XName.Get("gridCol", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), XmlConvert.ToString(columnWidths[i]))));
newTable.Add(tableGrid);*/
for (int i = 0; i < rowCount; i++)
{
XElement row = new XElement(XName.Get("tr", DocX.w.NamespaceName));
for (int j = 0; j < columnWidths.Length; j++)
{
XElement cell = CreateTableCell();
row.Add(cell);
}
newTable.Add(row);
}
return newTable;
}
/// <summary>
/// Create and return a cell of a table
/// </summary>
internal static XElement CreateTableCell(double w = 2310)
{
return new XElement
(
XName.Get("tc", DocX.w.NamespaceName),
new XElement(XName.Get("tcPr", DocX.w.NamespaceName),
new XElement(XName.Get("tcW", DocX.w.NamespaceName),
new XAttribute(XName.Get("w", DocX.w.NamespaceName), w),
new XAttribute(XName.Get("type", DocX.w.NamespaceName), "dxa"))),
new XElement(XName.Get("p", DocX.w.NamespaceName),
new XElement(XName.Get("pPr", DocX.w.NamespaceName)))
);
}
internal static List CreateItemInList(List list, string listText, int level = 0, ListItemType listType = ListItemType.Numbered, int? startNumber = null, bool trackChanges = false, bool continueNumbering = false)
{
if (list.NumId == 0)
{
list.CreateNewNumberingNumId(level, listType, startNumber, continueNumbering);
}
if (listText != null) //I see no reason why you shouldn't be able to insert an empty element. It simplifies tasks such as populating an item from html.
{
var newParagraphSection = new XElement
(
XName.Get("p", DocX.w.NamespaceName),
new XElement(XName.Get("pPr", DocX.w.NamespaceName),
new XElement(XName.Get("numPr", DocX.w.NamespaceName),
new XElement(XName.Get("ilvl", DocX.w.NamespaceName), new XAttribute(DocX.w + "val", level)),
new XElement(XName.Get("numId", DocX.w.NamespaceName), new XAttribute(DocX.w + "val", list.NumId)))),
new XElement(XName.Get("r", DocX.w.NamespaceName), new XElement(XName.Get("t", DocX.w.NamespaceName), listText))
);
if (trackChanges)
newParagraphSection = CreateEdit(EditType.ins, DateTime.Now, newParagraphSection);
if (startNumber == null)
{
list.AddItem(new Paragraph(list.Document, newParagraphSection, 0, ContainerType.Paragraph));
}
else
{
list.AddItemWithStartValue(new Paragraph(list.Document, newParagraphSection, 0, ContainerType.Paragraph), (int)startNumber);
}
}
return list;
}
internal static void RenumberIDs(DocX document)
{
IEnumerable<XAttribute> trackerIDs =
(from d in document.mainDoc.Descendants()
where d.Name.LocalName == "ins" || d.Name.LocalName == "del"
select d.Attribute(XName.Get("id", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")));
for (int i = 0; i < trackerIDs.Count(); i++)
trackerIDs.ElementAt(i).Value = i.ToString();
}
internal static Paragraph GetFirstParagraphEffectedByInsert(DocX document, int index)
{
// This document contains no Paragraphs and insertion is at index 0
if (document.Paragraphs.Count() == 0 && index == 0)
return null;
foreach (Paragraph p in document.Paragraphs)
{
if (p.endIndex >= index)
return p;
}
throw new ArgumentOutOfRangeException();
}
internal static List<XElement> FormatInput(string text, XElement rPr)
{
List<XElement> newRuns = new List<XElement>();
XElement tabRun = new XElement(DocX.w + "tab");
XElement breakRun = new XElement(DocX.w + "br");
StringBuilder sb = new StringBuilder();
if (string.IsNullOrEmpty(text))
{
return newRuns; //I dont wanna get an exception if text == null, so just return empy list
}
char lastChar = '\0';
foreach (char c in text)
{
switch (c)
{
case '\t':
if (sb.Length > 0)
{
XElement t = new XElement(DocX.w + "t", sb.ToString());
Novacode.Text.PreserveSpace(t);
newRuns.Add(new XElement(DocX.w + "r", rPr, t));
sb = new StringBuilder();
}
newRuns.Add(new XElement(DocX.w + "r", rPr, tabRun));
break;
case '\r':
if (sb.Length > 0)
{
XElement t = new XElement(DocX.w + "t", sb.ToString());
Novacode.Text.PreserveSpace(t);
newRuns.Add(new XElement(DocX.w + "r", rPr, t));
sb = new StringBuilder();
}
newRuns.Add(new XElement(DocX.w + "r", rPr, breakRun));
break;
case '\n':
if (lastChar == '\r') break;
if (sb.Length > 0)
{
XElement t = new XElement(DocX.w + "t", sb.ToString());
Novacode.Text.PreserveSpace(t);
newRuns.Add(new XElement(DocX.w + "r", rPr, t));
sb = new StringBuilder();
}
newRuns.Add(new XElement(DocX.w + "r", rPr, breakRun));
break;
default:
// Check the character against restricted list:
// RestrictedChar ::= [#x1-#x8] | [#xB-#xC] | [#xE-#x1F] | [#x7F-#x84] | [#x86-#x9F]
// See https://www.w3.org/TR/xml11/#sec-xml11
if( RestrictedXmlChar.Contains( c ) )
{
// skip the character
}
else
sb.Append(c);
break;
}
lastChar = c;
}
if (sb.Length > 0)
{
XElement t = new XElement(DocX.w + "t", sb.ToString());
Novacode.Text.PreserveSpace(t);
newRuns.Add(new XElement(DocX.w + "r", rPr, t));
}
return newRuns;
}
internal static XElement[] SplitParagraph(Paragraph p, int index)
{
// In this case edit dosent really matter, you have a choice.
Run r = p.GetFirstRunEffectedByEdit(index, EditType.ins);
XElement[] split;
XElement before, after;
if (r.Xml.Parent.Name.LocalName == "ins")
{
split = p.SplitEdit(r.Xml.Parent, index, EditType.ins);
before = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsBeforeSelf(), split[0]);
after = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsAfterSelf(), split[1]);
}
else if (r.Xml.Parent.Name.LocalName == "del")
{
split = p.SplitEdit(r.Xml.Parent, index, EditType.del);
before = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsBeforeSelf(), split[0]);
after = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsAfterSelf(), split[1]);
}
else
{
split = Run.SplitRun(r, index);
before = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.ElementsBeforeSelf(), split[0]);
after = new XElement(p.Xml.Name, p.Xml.Attributes(), split[1], r.Xml.ElementsAfterSelf());
}
if (before.Elements().Count() == 0)
before = null;
if (after.Elements().Count() == 0)
after = null;
return new XElement[] { before, after };
}
/// <!--
/// Bug found and fixed by trnilse. To see the change,
/// please compare this release to the previous release using TFS compare.
/// -->
internal static bool IsSameFile(Stream streamOne, Stream streamTwo)
{
int file1byte, file2byte;
if (streamOne.Length != streamTwo.Length)
{
// Return false to indicate files are different
return false;
}
// Read and compare a byte from each file until either a
// non-matching set of bytes is found or until the end of
// file1 is reached.
do
{
// Read one byte from each file.
file1byte = streamOne.ReadByte();
file2byte = streamTwo.ReadByte();
}
while ((file1byte == file2byte) && (file1byte != -1));
// Return the success of the comparison. "file1byte" is
// equal to "file2byte" at this point only if the files are
// the same.
streamOne.Position = 0;
streamTwo.Position = 0;
return ((file1byte - file2byte) == 0);
}
internal static UnderlineStyle GetUnderlineStyle(string underlineStyle)
{
switch (underlineStyle)
{
case "single":
return UnderlineStyle.singleLine;
case "double":
return UnderlineStyle.doubleLine;
case "thick":
return UnderlineStyle.thick;
case "dotted":
return UnderlineStyle.dotted;
case "dottedHeavy":
return UnderlineStyle.dottedHeavy;
case "dash":
return UnderlineStyle.dash;
case "dashedHeavy":
return UnderlineStyle.dashedHeavy;
case "dashLong":
return UnderlineStyle.dashLong;
case "dashLongHeavy":
return UnderlineStyle.dashLongHeavy;
case "dotDash":
return UnderlineStyle.dotDash;
case "dashDotHeavy":
return UnderlineStyle.dashDotHeavy;
case "dotDotDash":
return UnderlineStyle.dotDotDash;
case "dashDotDotHeavy":
return UnderlineStyle.dashDotDotHeavy;
case "wave":
return UnderlineStyle.wave;
case "wavyHeavy":
return UnderlineStyle.wavyHeavy;
case "wavyDouble":
return UnderlineStyle.wavyDouble;
case "words":
return UnderlineStyle.words;
default:
return UnderlineStyle.none;
}
}
}
}

+ 0
- 232
DocX/Hyperlink.cs View File

@@ -1,232 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO.Packaging;
namespace Novacode
{
/// <summary>
/// Represents a Hyperlink in a document.
/// </summary>
public class Hyperlink: DocXElement
{
internal Uri uri;
internal String text;
internal Dictionary<PackagePart, PackageRelationship> hyperlink_rels;
internal int type;
internal String id;
internal XElement instrText;
internal List<XElement> runs;
/// <summary>
/// Remove a Hyperlink from this Paragraph only.
/// </summary>
/// <example>
/// <code>
/// // Create a document.
/// using (DocX document = DocX.Create(@"Test.docx"))
/// {
/// // Add a hyperlink to this document.
/// Hyperlink h = document.AddHyperlink("link", new Uri("http://www.google.com"));
///
/// // Add a Paragraph to this document and insert the hyperlink
/// Paragraph p1 = document.InsertParagraph();
/// p1.Append("This is a cool ").AppendHyperlink(h).Append(" .");
///
/// /*
/// * Remove the hyperlink from this Paragraph only.
/// * Note a reference to the hyperlink will still exist in the document and it can thus be reused.
/// */
/// p1.Hyperlinks[0].Remove();
///
/// // Add a new Paragraph to this document and reuse the hyperlink h.
/// Paragraph p2 = document.InsertParagraph();
/// p2.Append("This is the same cool ").AppendHyperlink(h).Append(" .");
///
/// document.Save();
/// }// Release this document from memory.
/// </code>
/// </example>
public void Remove()
{
Xml.Remove();
}
/// <summary>
/// Change the Text of a Hyperlink.
/// </summary>
/// <example>
/// Change the Text of a Hyperlink.
/// <code>
/// // Create a document.
/// using (DocX document = DocX.Load(@"Test.docx"))
/// {
/// // Get all of the hyperlinks in this document
/// List&lt;Hyperlink&gt; hyperlinks = document.Hyperlinks;
///
/// // Change the first hyperlinks text and Uri
/// Hyperlink h0 = hyperlinks[0];
/// h0.Text = "DocX";
/// h0.Uri = new Uri("http://docx.codeplex.com");
///
/// // Save this document.
/// document.Save();
/// }
/// </code>
/// </example>
public string Text
{
get
{
return this.text;
}
set
{
XElement rPr =
new XElement
(
DocX.w + "rPr",
new XElement
(
DocX.w + "rStyle",
new XAttribute(DocX.w + "val", "Hyperlink")
)
);
// Format and add the new text.
List<XElement> newRuns = HelperFunctions.FormatInput(value, rPr);
if (type == 0)
{
// Get all the runs in this Text.
var runs = from r in Xml.Elements()
where r.Name.LocalName == "r"
select r;
// Remove each run.
for (int i = 0; i < runs.Count(); i++)
runs.Remove();
Xml.Add(newRuns);
}
else
{
XElement separate = XElement.Parse(@"
<w:r xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
<w:fldChar w:fldCharType='separate'/>
</w:r>");
XElement end = XElement.Parse(@"
<w:r xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
<w:fldChar w:fldCharType='end' />
</w:r>");
runs.Last().AddAfterSelf(separate, newRuns, end);
runs.ForEach(r => r.Remove());
}
this.text = value;
}
}
/// <summary>
/// Change the Uri of a Hyperlink.
/// </summary>
/// <example>
/// Change the Uri of a Hyperlink.
/// <code>
/// <![CDATA[
/// // Create a document.
/// using (DocX document = DocX.Load(@"Test.docx"))
/// {
/// // Get all of the hyperlinks in this document
/// List<Hyperlink> hyperlinks = document.Hyperlinks;
///
/// // Change the first hyperlinks text and Uri
/// Hyperlink h0 = hyperlinks[0];
/// h0.Text = "DocX";
/// h0.Uri = new Uri("http://docx.codeplex.com");
///
/// // Save this document.
/// document.Save();
/// }
/// ]]>
/// </code>
/// </example>
public Uri Uri
{
get
{
if (type == 0 && id != String.Empty)
{
PackageRelationship r = mainPart.GetRelationship(id);
return r.TargetUri;
}
return this.uri;
}
set
{
if (type == 0)
{
PackageRelationship r = mainPart.GetRelationship(id);
// Get all of the information about this relationship.
TargetMode r_tm = r.TargetMode;
string r_rt = r.RelationshipType;
string r_id = r.Id;
// Delete the relationship
mainPart.DeleteRelationship(r_id);
mainPart.CreateRelationship(value, r_tm, r_rt, r_id);
}
else
{
instrText.Value = "HYPERLINK " + "\"" + value + "\"";
}
this.uri = value;
}
}
internal Hyperlink(DocX document, PackagePart mainPart, XElement i): base(document, i)
{
this.type = 0;
this.id = i.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
StringBuilder sb = new StringBuilder();
HelperFunctions.GetTextRecursive(i, ref sb);
this.text = sb.ToString();
}
internal Hyperlink(DocX document, XElement instrText, List<XElement> runs) : base(document, null)
{
this.type = 1;
this.instrText = instrText;
this.runs = runs;
try
{
int start = instrText.Value.IndexOf("HYPERLINK \"") + "HYPERLINK \"".Length;
int end = instrText.Value.IndexOf("\"", start);
if (start != -1 && end != -1)
{
this.uri = new Uri(instrText.Value.Substring(start, end - start), UriKind.Absolute);
StringBuilder sb = new StringBuilder();
HelperFunctions.GetTextRecursive(new XElement(XName.Get("temp", DocX.w.NamespaceName), runs), ref sb);
this.text = sb.ToString();
}
}
catch (Exception e){throw e;}
}
}
}

+ 0
- 9
DocX/IContentContainer.cs View File

@@ -1,9 +0,0 @@
using System.Collections.ObjectModel;

namespace Novacode
{
interface IContentContainer
{
ReadOnlyCollection<Content> Paragraphs { get; }
}
}

+ 0
- 9
DocX/IParagraphContainer.cs View File

@@ -1,9 +0,0 @@
using System.Collections.ObjectModel;
namespace Novacode
{
public interface IParagraphContainer
{
ReadOnlyCollection<Paragraph> Paragraphs { get; }
}
}

+ 0
- 96
DocX/Image.cs View File

@@ -1,96 +0,0 @@
using System;
using System.IO.Packaging;
using System.IO;
namespace Novacode
{
/// <summary>
/// Represents an Image embedded in a document.
/// </summary>
public class Image
{
/// <summary>
/// A unique id which identifies this Image.
/// </summary>
private string id;
private DocX document;
internal PackageRelationship pr;
public Stream GetStream(FileMode mode, FileAccess access)
{
string temp = pr.SourceUri.OriginalString;
string start = temp.Remove(temp.LastIndexOf('/'));
string end = pr.TargetUri.OriginalString;
string full = end.Contains(start) ? end : start + "/" + end;
return (new PackagePartStream(document.package.GetPart(new Uri(full, UriKind.Relative)).GetStream(mode, access)));
}
/// <summary>
/// Returns the id of this Image.
/// </summary>
public string Id
{
get {return id;}
}
internal Image(DocX document, PackageRelationship pr)
{
this.document = document;
this.pr = pr;
this.id = pr.Id;
}
/// <summary>
/// Add an image to a document, create a custom view of that image (picture) and then insert it into a Paragraph using append.
/// </summary>
/// <returns></returns>
/// <example>
/// Add an image to a document, create a custom view of that image (picture) and then insert it into a Paragraph using append.
/// <code>
/// using (DocX document = DocX.Create("Test.docx"))
/// {
/// // Add an image to the document.
/// Image i = document.AddImage(@"Image.jpg");
///
/// // Create a picture i.e. (A custom view of an image)
/// Picture p = i.CreatePicture();
/// p.FlipHorizontal = true;
/// p.Rotation = 10;
///
/// // Create a new Paragraph.
/// Paragraph par = document.InsertParagraph();
///
/// // Append content to the Paragraph.
/// par.Append("Here is a cool picture")
/// .AppendPicture(p)
/// .Append(" don't you think so?");
///
/// // Save all changes made to this document.
/// document.Save();
/// }
/// </code>
/// </example>
public Picture CreatePicture()
{
return Paragraph.CreatePicture(document, id, string.Empty, string.Empty);
}
public Picture CreatePicture(int height, int width) {
Picture picture = Paragraph.CreatePicture(document, id, string.Empty, string.Empty);
picture.Height = height;
picture.Width = width;
return picture;
}
///<summary>
/// Returns the name of the image file.
///</summary>
public string FileName
{
get
{
return Path.GetFileName(this.pr.TargetUri.ToString());
}
}
}
}

BIN
DocX/KeyWithoutPassword.snk View File


+ 0
- 7
DocX/License/License.html View File

@@ -1,7 +0,0 @@
<html>
<body>
<div id="licenseTextHolder" style="margin: 1em">
<span id="ctl00_ctl00_MasterContent_Content_licenseText">Microsoft Public License &#40;Ms-PL&#41;<br /><br />This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.<br /><br />1. Definitions<br /><br />The terms &#34;reproduce,&#34; &#34;reproduction,&#34; &#34;derivative works,&#34; and &#34;distribution&#34; have the same meaning here as under U.S. copyright law.<br /><br />A &#34;contribution&#34; is the original software, or any additions or changes to the software.<br /><br />A &#34;contributor&#34; is any person that distributes its contribution under this license.<br /><br />&#34;Licensed patents&#34; are a contributor&#39;s patent claims that read directly on its contribution.<br /><br />2. Grant of Rights<br /><br />&#40;A&#41; Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.<br /><br />&#40;B&#41; Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and&#47;or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.<br /><br />3. Conditions and Limitations<br /><br />&#40;A&#41; No Trademark License- This license does not grant you rights to use any contributors&#39; name, logo, or trademarks.<br /><br />&#40;B&#41; If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.<br /><br />&#40;C&#41; If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.<br /><br />&#40;D&#41; If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.<br /><br />&#40;E&#41; The software is licensed &#34;as-is.&#34; You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.</span>
</div>
</body>
</html><!-- @SortOrder 2 -->

+ 0
- 233
DocX/List.cs View File

@@ -1,233 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Novacode
{
/// <summary>
/// Represents a List in a document.
/// </summary>
public class List : InsertBeforeOrAfter
{
/// <summary>
/// This is a list of paragraphs that will be added to the document
/// when the list is inserted into the document.
/// The paragraph needs a numPr defined to be in this items collection.
/// </summary>
public List<Paragraph> Items { get; private set; }
/// <summary>
/// The numId used to reference the list settings in the numbering.xml
/// </summary>
public int NumId { get; private set; }
/// <summary>
/// The ListItemType (bullet or numbered) of the list.
/// </summary>
public ListItemType? ListType { get; private set; }

internal List(DocX document, XElement xml)
: base(document, xml)
{
Items = new List<Paragraph>();
ListType = null;
}

/// <summary>
/// Adds an item to the list.
/// </summary>
/// <param name="paragraph"></param>
/// <exception cref="InvalidOperationException">
/// Throws an InvalidOperationException if the item cannot be added to the list.
/// </exception>
public void AddItem(Paragraph paragraph)
{
if (paragraph.IsListItem)
{
var numIdNode = paragraph.Xml.Descendants().First(s => s.Name.LocalName == "numId");
var numId = Int32.Parse(numIdNode.Attribute(DocX.w + "val").Value);

if (CanAddListItem(paragraph))
{
NumId = numId;
Items.Add(paragraph);
}
else
throw new InvalidOperationException("New list items can only be added to this list if they are have the same numId.");
}
}

public void AddItemWithStartValue(Paragraph paragraph, int start)
{
//TODO: Update the numbering
UpdateNumberingForLevelStartNumber(int.Parse(paragraph.IndentLevel.ToString()), start);
if (ContainsLevel(start))
throw new InvalidOperationException("Cannot add a paragraph with a start value if another element already exists in this list with that level.");
AddItem(paragraph);
}

private void UpdateNumberingForLevelStartNumber(int iLevel, int start)
{
var abstractNum = GetAbstractNum(NumId);
var level = abstractNum.Descendants().First(el => el.Name.LocalName == "lvl" && el.GetAttribute(DocX.w + "ilvl") == iLevel.ToString());
level.Descendants().First(el => el.Name.LocalName == "start").SetAttributeValue(DocX.w + "val", start);
}

/// <summary>
/// Determine if it is able to add the item to the list
/// </summary>
/// <param name="paragraph"></param>
/// <returns>
/// Return true if AddItem(...) will succeed with the given paragraph.
/// </returns>
public bool CanAddListItem(Paragraph paragraph)
{
if (paragraph.IsListItem)
{
//var lvlNode = paragraph.Xml.Descendants().First(s => s.Name.LocalName == "ilvl");
var numIdNode = paragraph.Xml.Descendants().First(s => s.Name.LocalName == "numId");
var numId = Int32.Parse(numIdNode.Attribute(DocX.w + "val").Value);

//Level = Int32.Parse(lvlNode.Attribute(DocX.w + "val").Value);
if (NumId == 0 || (numId == NumId && numId > 0))
{
return true;
}
}
return false;
}

public bool ContainsLevel(int ilvl)
{
return Items.Any(i => i.ParagraphNumberProperties.Descendants().First(el => el.Name.LocalName == "ilvl").Value == ilvl.ToString());
}
internal void CreateNewNumberingNumId(int level = 0, ListItemType listType = ListItemType.Numbered, int? startNumber = null, bool continueNumbering = false)
{
ValidateDocXNumberingPartExists();
if (Document.numbering.Root == null)
{
throw new InvalidOperationException("Numbering section did not instantiate properly.");
}

ListType = listType;

var numId = GetMaxNumId() + 1;
var abstractNumId = GetMaxAbstractNumId() + 1;

XDocument listTemplate;
switch (listType)
{
case ListItemType.Bulleted:
listTemplate = HelperFunctions.DecompressXMLResource("Novacode.Resources.numbering.default_bullet_abstract.xml.gz");
break;
case ListItemType.Numbered:
listTemplate = HelperFunctions.DecompressXMLResource("Novacode.Resources.numbering.default_decimal_abstract.xml.gz");
break;
default:
throw new InvalidOperationException(string.Format("Unable to deal with ListItemType: {0}.", listType.ToString()));
}
var abstractNumTemplate = listTemplate.Descendants().Single(d => d.Name.LocalName == "abstractNum");
abstractNumTemplate.SetAttributeValue(DocX.w + "abstractNumId", abstractNumId);
//Fixing an issue where numbering would continue from previous numbered lists. Setting startOverride assures that a numbered list starts on the provided number.
//The override needs only be on level 0 as this will cascade to the rest of the list.
var abstractNumXml = GetAbstractNumXml(abstractNumId, numId, startNumber, continueNumbering);

var abstractNumNode = Document.numbering.Root.Descendants().LastOrDefault(xElement => xElement.Name.LocalName == "abstractNum");
var numXml = Document.numbering.Root.Descendants().LastOrDefault(xElement => xElement.Name.LocalName == "num");

if (abstractNumNode == null || numXml == null)
{
Document.numbering.Root.Add(abstractNumTemplate);
Document.numbering.Root.Add(abstractNumXml);
}
else
{
abstractNumNode.AddAfterSelf(abstractNumTemplate);
numXml.AddAfterSelf(
abstractNumXml
);
}

NumId = numId;
}
private XElement GetAbstractNumXml(int abstractNumId, int numId, int? startNumber, bool continueNumbering)
{
//Fixing an issue where numbering would continue from previous numbered lists. Setting startOverride assures that a numbered list starts on the provided number.
//The override needs only be on level 0 as this will cascade to the rest of the list.
var startOverride = new XElement(XName.Get("startOverride", DocX.w.NamespaceName), new XAttribute(DocX.w + "val", startNumber ?? 1));
var lvlOverride = new XElement(XName.Get("lvlOverride", DocX.w.NamespaceName), new XAttribute(DocX.w + "ilvl", 0), startOverride);
var abstractNumIdElement = new XElement(XName.Get("abstractNumId", DocX.w.NamespaceName), new XAttribute(DocX.w + "val", abstractNumId));
return continueNumbering
? new XElement(XName.Get("num", DocX.w.NamespaceName), new XAttribute(DocX.w + "numId", numId), abstractNumIdElement)
: new XElement(XName.Get("num", DocX.w.NamespaceName), new XAttribute(DocX.w + "numId", numId), abstractNumIdElement, lvlOverride);
}

/// <summary>
/// Method to determine the last numId for a list element.
/// Also useful for determining the next numId to use for inserting a new list element into the document.
/// </summary>
/// <returns>
/// 0 if there are no elements in the list already.
/// Increment the return for the next valid value of a new list element.
/// </returns>
private int GetMaxNumId()
{
const int defaultValue = 0;
if (Document.numbering == null)
return defaultValue;

var numlist = Document.numbering.Descendants().Where(d => d.Name.LocalName == "num").ToList();
if (numlist.Any())
return numlist.Attributes(DocX.w + "numId").Max(e => int.Parse(e.Value));
return defaultValue;
}

/// <summary>
/// Method to determine the last abstractNumId for a list element.
/// Also useful for determining the next abstractNumId to use for inserting a new list element into the document.
/// </summary>
/// <returns>
/// -1 if there are no elements in the list already.
/// Increment the return for the next valid value of a new list element.
/// </returns>
private int GetMaxAbstractNumId()
{
const int defaultValue = -1;

if (Document.numbering == null)
return defaultValue;

var numlist = Document.numbering.Descendants().Where(d => d.Name.LocalName == "abstractNum").ToList();
if (numlist.Any())
{
var maxAbstractNumId = numlist.Attributes(DocX.w + "abstractNumId").Max(e => int.Parse(e.Value));
return maxAbstractNumId;
}
return defaultValue;
}

/// <summary>
/// Get the abstractNum definition for the given numId
/// </summary>
/// <param name="numId">The numId on the pPr element</param>
/// <returns>XElement representing the requested abstractNum</returns>
internal XElement GetAbstractNum(int numId)
{
var num = Document.numbering.Descendants().First(d => d.Name.LocalName == "num" && d.GetAttribute(DocX.w + "numId").Equals(numId.ToString()));
var abstractNumId = num.Descendants().First(d => d.Name.LocalName == "abstractNumId");
return Document.numbering.Descendants().First(d => d.Name.LocalName == "abstractNum" && d.GetAttribute("abstractNumId").Equals(abstractNumId.Value));
}

private void ValidateDocXNumberingPartExists()
{
var numberingUri = new Uri("/word/numbering.xml", UriKind.Relative);

// If the internal document contains no /word/numbering.xml create one.
if (!Document.package.PartExists(numberingUri))
Document.numbering = HelperFunctions.AddDefaultNumberingXml(Document.package);
}
}
}

+ 0
- 87
DocX/PackagePartStream.cs View File

@@ -1,87 +0,0 @@
using System.IO;

namespace Novacode
{
/// <summary>
/// OpenXML Isolated Storage access is not thread safe.
/// Use app domain wide lock for writing.
/// </summary>
public class PackagePartStream : Stream
{
private static readonly object lockObject = new object();

private readonly Stream stream;

public PackagePartStream(Stream stream)
{
this.stream = stream;
}

public override bool CanRead
{
get { return this.stream.CanRead; }
}

public override bool CanSeek
{
get { return this.stream.CanSeek; }
}

public override bool CanWrite
{
get { return this.stream.CanWrite; }
}

public override long Length
{
get { return this.stream.Length; }
}

public override long Position
{
get { return this.stream.Position; }
set { this.stream.Position = value; }
}

public override long Seek(long offset, SeekOrigin origin)
{
return this.stream.Seek(offset, origin);
}

public override void SetLength(long value)
{
this.stream.SetLength(value);
}

public override int Read(byte[] buffer, int offset, int count)
{
return this.stream.Read(buffer, offset, count);
}

public override void Write(byte[] buffer, int offset, int count)
{
lock (lockObject)
{
this.stream.Write(buffer, offset, count);
}
}

public override void Flush()
{
lock (lockObject)
{
this.stream.Flush();
}
}

public override void Close()
{
this.stream.Close();
}

protected override void Dispose(bool disposing)
{
this.stream.Dispose();
}
}
}

+ 0
- 74
DocX/PageLayout.cs View File

@@ -1,74 +0,0 @@
using System;
using System.Xml.Linq;
namespace Novacode
{
public class PageLayout: DocXElement
{
internal PageLayout(DocX document, XElement xml):base(document, xml)
{
}
public Orientation Orientation
{
get
{
/*
* Get the pgSz (page size) element for this Section,
* null will be return if no such element exists.
*/
XElement pgSz = Xml.Element(XName.Get("pgSz", DocX.w.NamespaceName));
if (pgSz == null)
return Orientation.Portrait;
// Get the attribute of the pgSz element.
XAttribute val = pgSz.Attribute(XName.Get("orient", DocX.w.NamespaceName));
// If val is null, this cell contains no information.
if (val == null)
return Orientation.Portrait;
if (val.Value.Equals("Landscape", StringComparison.CurrentCultureIgnoreCase))
return Orientation.Landscape;
else
return Orientation.Portrait;
}
set
{
// Check if already correct value.
if (Orientation == value)
return;
/*
* Get the pgSz (page size) element for this Section,
* null will be return if no such element exists.
*/
XElement pgSz = Xml.Element(XName.Get("pgSz", DocX.w.NamespaceName));
if (pgSz == null)
{
Xml.SetElementValue(XName.Get("pgSz", DocX.w.NamespaceName), string.Empty);
pgSz = Xml.Element(XName.Get("pgSz", DocX.w.NamespaceName));
}
pgSz.SetAttributeValue(XName.Get("orient", DocX.w.NamespaceName), value.ToString().ToLower());
if(value == Novacode.Orientation.Landscape)
{
pgSz.SetAttributeValue(XName.Get("w", DocX.w.NamespaceName), "16838");
pgSz.SetAttributeValue(XName.Get("h", DocX.w.NamespaceName), "11906");
}
else if (value == Novacode.Orientation.Portrait)
{
pgSz.SetAttributeValue(XName.Get("w", DocX.w.NamespaceName), "11906");
pgSz.SetAttributeValue(XName.Get("h", DocX.w.NamespaceName), "16838");
}
}
}
}
}

+ 0
- 4732
DocX/Paragraph.cs
File diff suppressed because it is too large
View File


+ 0
- 421
DocX/Picture.cs View File

@@ -1,421 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.IO.Packaging;
namespace Novacode
{
/// <summary>
/// Represents a Picture in this document, a Picture is a customized view of an Image.
/// </summary>
public class Picture: DocXElement
{
private const int EmusInPixel = 9525;
internal Dictionary<PackagePart, PackageRelationship> picture_rels;
internal Image img;
private string id;
private string name;
private string descr;
private int cx, cy;
//private string fileName;
private uint rotation;
private bool hFlip, vFlip;
private object pictureShape;
private XElement xfrm;
private XElement prstGeom;
/// <summary>
/// Remove this Picture from this document.
/// </summary>
public void Remove()
{
Xml.Remove();
}
/// <summary>
/// Wraps an XElement as an Image
/// </summary>
/// <param name="document"></param>
/// <param name="i">The XElement i to wrap</param>
/// <param name="img"></param>
internal Picture(DocX document, XElement i, Image img):base(document, i)
{
picture_rels = new Dictionary<PackagePart, PackageRelationship>();
this.img = img;
this.id =
(
from e in Xml.Descendants()
where e.Name.LocalName.Equals("blip")
select e.Attribute(XName.Get("embed", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")).Value
).SingleOrDefault();
if (this.id == null)
{
this.id =
(
from e in Xml.Descendants()
where e.Name.LocalName.Equals("imagedata")
select e.Attribute(XName.Get("id", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")).Value
).SingleOrDefault();
}
this.name =
(
from e in Xml.Descendants()
let a = e.Attribute(XName.Get("name"))
where (a != null)
select a.Value
).FirstOrDefault();
if (this.name == null)
{
this.name =
(
from e in Xml.Descendants()
let a = e.Attribute(XName.Get("title"))
where (a != null)
select a.Value
).FirstOrDefault();
}
this.descr =
(
from e in Xml.Descendants()
let a = e.Attribute(XName.Get("descr"))
where (a != null)
select a.Value
).FirstOrDefault();
this.cx =
(
from e in Xml.Descendants()
let a = e.Attribute(XName.Get("cx"))
where (a != null)
select int.Parse(a.Value)
).FirstOrDefault();
if (this.cx == 0)
{
XAttribute style =
(
from e in Xml.Descendants()
let a = e.Attribute(XName.Get("style"))
where (a != null)
select a
).FirstOrDefault();
string fromWidth = style.Value.Substring(style.Value.IndexOf("width:") + 6);
var widthInt = ((double.Parse((fromWidth.Substring(0, fromWidth.IndexOf("pt"))).Replace(".", ","))) / 72.0) * 914400;
cx = System.Convert.ToInt32(widthInt);
}
this.cy =
(
from e in Xml.Descendants()
let a = e.Attribute(XName.Get("cy"))
where (a != null)
select int.Parse(a.Value)
).FirstOrDefault();
if (this.cy == 0)
{
XAttribute style =
(
from e in Xml.Descendants()
let a = e.Attribute(XName.Get("style"))
where (a != null)
select a
).FirstOrDefault();
string fromHeight = style.Value.Substring(style.Value.IndexOf("height:") + 7);
var heightInt = ((double.Parse((fromHeight.Substring(0, fromHeight.IndexOf("pt"))).Replace(".", ","))) / 72.0) * 914400;
cy = System.Convert.ToInt32(heightInt);
}
this.xfrm =
(
from d in Xml.Descendants()
where d.Name.LocalName.Equals("xfrm")
select d
).SingleOrDefault();
this.prstGeom =
(
from d in Xml.Descendants()
where d.Name.LocalName.Equals("prstGeom")
select d
).SingleOrDefault();
if (xfrm != null)
this.rotation = xfrm.Attribute(XName.Get("rot")) == null ? 0 : uint.Parse(xfrm.Attribute(XName.Get("rot")).Value);
}
private void SetPictureShape(object shape)
{
this.pictureShape = shape;
XAttribute prst = prstGeom.Attribute(XName.Get("prst"));
if (prst == null)
prstGeom.Add(new XAttribute(XName.Get("prst"), "rectangle"));
prstGeom.Attribute(XName.Get("prst")).Value = shape.ToString();
}
/// <summary>
/// Set the shape of this Picture to one in the BasicShapes enumeration.
/// </summary>
/// <param name="shape">A shape from the BasicShapes enumeration.</param>
public void SetPictureShape(BasicShapes shape)
{
SetPictureShape((object)shape);
}
/// <summary>
/// Set the shape of this Picture to one in the RectangleShapes enumeration.
/// </summary>
/// <param name="shape">A shape from the RectangleShapes enumeration.</param>
public void SetPictureShape(RectangleShapes shape)
{
SetPictureShape((object)shape);
}
/// <summary>
/// Set the shape of this Picture to one in the BlockArrowShapes enumeration.
/// </summary>
/// <param name="shape">A shape from the BlockArrowShapes enumeration.</param>
public void SetPictureShape(BlockArrowShapes shape)
{
SetPictureShape((object)shape);
}
/// <summary>
/// Set the shape of this Picture to one in the EquationShapes enumeration.
/// </summary>
/// <param name="shape">A shape from the EquationShapes enumeration.</param>
public void SetPictureShape(EquationShapes shape)
{
SetPictureShape((object)shape);
}
/// <summary>
/// Set the shape of this Picture to one in the FlowchartShapes enumeration.
/// </summary>
/// <param name="shape">A shape from the FlowchartShapes enumeration.</param>
public void SetPictureShape(FlowchartShapes shape)
{
SetPictureShape((object)shape);
}
/// <summary>
/// Set the shape of this Picture to one in the StarAndBannerShapes enumeration.
/// </summary>
/// <param name="shape">A shape from the StarAndBannerShapes enumeration.</param>
public void SetPictureShape(StarAndBannerShapes shape)
{
SetPictureShape((object)shape);
}
/// <summary>
/// Set the shape of this Picture to one in the CalloutShapes enumeration.
/// </summary>
/// <param name="shape">A shape from the CalloutShapes enumeration.</param>
public void SetPictureShape(CalloutShapes shape)
{
SetPictureShape((object)shape);
}
/// <summary>
/// A unique id that identifies an Image embedded in this document.
/// </summary>
public string Id
{
get { return id; }
}
/// <summary>
/// Flip this Picture Horizontally.
/// </summary>
public bool FlipHorizontal
{
get { return hFlip; }
set
{
hFlip = value;
XAttribute flipH = xfrm.Attribute(XName.Get("flipH"));
if (flipH == null)
xfrm.Add(new XAttribute(XName.Get("flipH"), "0"));
xfrm.Attribute(XName.Get("flipH")).Value = hFlip ? "1" : "0";
}
}
/// <summary>
/// Flip this Picture Vertically.
/// </summary>
public bool FlipVertical
{
get { return vFlip; }
set
{
vFlip = value;
XAttribute flipV = xfrm.Attribute(XName.Get("flipV"));
if (flipV == null)
xfrm.Add(new XAttribute(XName.Get("flipV"), "0"));
xfrm.Attribute(XName.Get("flipV")).Value = vFlip ? "1" : "0";
}
}
/// <summary>
/// The rotation in degrees of this image, actual value = value % 360
/// </summary>
public uint Rotation
{
get { return rotation / 60000; }
set
{
rotation = (value % 360) * 60000;
XElement xfrm =
(from d in Xml.Descendants()
where d.Name.LocalName.Equals("xfrm")
select d).Single();
XAttribute rot = xfrm.Attribute(XName.Get("rot"));
if(rot == null)
xfrm.Add(new XAttribute(XName.Get("rot"), 0));
xfrm.Attribute(XName.Get("rot")).Value = rotation.ToString();
}
}
/// <summary>
/// Gets or sets the name of this Image.
/// </summary>
public string Name
{
get { return name; }
set
{
name = value;
foreach (XAttribute a in Xml.Descendants().Attributes(XName.Get("name")))
a.Value = name;
}
}
/// <summary>
/// Gets or sets the description for this Image.
/// </summary>
public string Description
{
get { return descr; }
set
{
descr = value;
foreach (XAttribute a in Xml.Descendants().Attributes(XName.Get("descr")))
a.Value = descr;
}
}
///<summary>
/// Returns the name of the image file for the picture.
///</summary>
public string FileName
{
get
{
return img.FileName;
}
}
/// <summary>
/// Get or sets the Width of this Image.
/// </summary>
public int Width
{
get { return cx / EmusInPixel; }
set
{
cx = value * EmusInPixel;
foreach (XAttribute a in Xml.Descendants().Attributes(XName.Get("cx")))
a.Value = (cx).ToString();
}
}
/// <summary>
/// Get or sets the height of this Image.
/// </summary>
public int Height
{
get { return cy / EmusInPixel; }
set
{
cy = value * EmusInPixel;
foreach (XAttribute a in Xml.Descendants().Attributes(XName.Get("cy")))
a.Value = (cy).ToString();
}
}
// refs:
// https://startbigthinksmall.wordpress.com/2010/01/04/points-inches-and-emus-measuring-units-in-office-open-xml/
// http://lcorneliussen.de/raw/dashboards/ooxml/
private const int InchToEmuFactor = 914400;
private const double EmuToInchFactor = 1d / InchToEmuFactor;
/// <summary>
/// Get or sets the Width of this Image (inches).
/// </summary>
public double WidthInches
{
get
{
return Width * EmusInPixel * EmuToInchFactor;
}
set
{
Width = (int)(value * InchToEmuFactor / EmusInPixel);
}
}
/// <summary>
/// Get or sets the Height of this Image (inches).
/// </summary>
public double HeightInches
{
get
{
return Height * EmusInPixel * EmuToInchFactor;
}
set
{
Height = (int)(value * InchToEmuFactor / EmusInPixel);
}
}
//public void Delete()
//{
// // Remove xml
// i.Remove();
// // Rebuild the image collection for this paragraph
// // Requires that every Image have a link to its paragraph
//}
}
}

+ 0
- 44
DocX/Properties/AssemblyInfo.cs View File

@@ -1,44 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Docx")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DocX")]
[assembly: AssemblyProduct("Docx")]
[assembly: AssemblyCopyright("DocX @ 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Allow the UnitTests to get at internal stuff.
[assembly: InternalsVisibleTo( "UnitTests, PublicKey=" +
"0024000004800000940000000602000000240000525341310004000001000100b739555cdacfd1" +
"f59b61e7fb189ed886849ae10d0f8a876cd700d36286addf1d4a6854bb23b12fad5700b64787e9" +
"9b0b9f0ed0d64d86d591a32e58080470bdc9a61845301edf6cbb447c3578718763d3f93694a2ac" +
"fdac1c2d096343f3d7085ea1c20fcfeb1d8bac4153204c9faa40c29be2dc38056116e756ff7bbf" +
"9d82e3ab" )]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("16123f21-f3d1-47bb-ae9a-eb7c82c0f3c8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.23")]
[assembly: AssemblyFileVersion("1.0.0.23")]

+ 0
- 17
DocX/Section.cs View File

@@ -1,17 +0,0 @@
using System.Collections.Generic;
using System.Xml.Linq;

namespace Novacode
{
public class Section : Container
{

public SectionBreakType SectionBreakType;

internal Section(DocX document, XElement xml) : base(document, xml)
{
}

public List<Paragraph> SectionParagraphs { get; set; }
}
}

+ 0
- 3910
DocX/Table.cs
File diff suppressed because it is too large
View File


+ 0
- 103
DocX/TableOfContents.cs View File

@@ -1,103 +0,0 @@
using System;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
namespace Novacode
{
/// <summary>
/// Represents a table of contents in the document
/// </summary>
public class TableOfContents : DocXElement
{
#region TocBaseValues
private const string HeaderStyle = "TOCHeading";
private const int RightTabPos = 9350;
#endregion
private TableOfContents(DocX document, XElement xml, string headerStyle) : base(document, xml)
{
AssureUpdateField(document);
AssureStyles(document, headerStyle);
}
internal static TableOfContents CreateTableOfContents(DocX document, string title, TableOfContentsSwitches switches, string headerStyle = null, int lastIncludeLevel = 3, int? rightTabPos = null)
{
var reader = XmlReader.Create(new StringReader(string.Format(XmlTemplateBases.TocXmlBase, headerStyle ?? HeaderStyle, title, rightTabPos ?? RightTabPos, BuildSwitchString(switches, lastIncludeLevel))));
var xml = XElement.Load(reader);
return new TableOfContents(document, xml, headerStyle);
}
private void AssureUpdateField(DocX document)
{
if (document.settings.Descendants().Any(x => x.Name.Equals(DocX.w + "updateFields"))) return;
var element = new XElement(XName.Get("updateFields", DocX.w.NamespaceName), new XAttribute(DocX.w + "val", true));
document.settings.Root.Add(element);
}
private void AssureStyles(DocX document, string headerStyle)
{
if (!HasStyle(document, headerStyle, "paragraph"))
{
var reader = XmlReader.Create(new StringReader(string.Format(XmlTemplateBases.TocHeadingStyleBase, headerStyle ?? HeaderStyle)));
var xml = XElement.Load(reader);
document.styles.Root.Add(xml);
}
if (!HasStyle(document, "TOC1", "paragraph"))
{
var reader = XmlReader.Create(new StringReader(string.Format(XmlTemplateBases.TocElementStyleBase, "TOC1", "toc 1")));
var xml = XElement.Load(reader);
document.styles.Root.Add(xml);
}
if (!HasStyle(document, "TOC2", "paragraph"))
{
var reader = XmlReader.Create(new StringReader(string.Format(XmlTemplateBases.TocElementStyleBase, "TOC2", "toc 2")));
var xml = XElement.Load(reader);
document.styles.Root.Add(xml);
}
if (!HasStyle(document, "TOC3", "paragraph"))
{
var reader = XmlReader.Create(new StringReader(string.Format(XmlTemplateBases.TocElementStyleBase, "TOC3", "toc 3")));
var xml = XElement.Load(reader);
document.styles.Root.Add(xml);
}
if (!HasStyle(document, "TOC4", "paragraph"))
{
var reader = XmlReader.Create(new StringReader(string.Format(XmlTemplateBases.TocElementStyleBase, "TOC4", "toc 4")));
var xml = XElement.Load(reader);
document.styles.Root.Add(xml);
}
if (!HasStyle(document, "Hyperlink", "character"))
{
var reader = XmlReader.Create(new StringReader(string.Format(XmlTemplateBases.TocHyperLinkStyleBase)));
var xml = XElement.Load(reader);
document.styles.Root.Add(xml);
}
}
private bool HasStyle(DocX document, string value, string type)
{
return document.styles.Descendants().Any(x => x.Name.Equals(DocX.w + "style")&& (x.Attribute(DocX.w + "type") == null || x.Attribute(DocX.w + "type").Value.Equals(type)) && x.Attribute(DocX.w + "styleId") != null && x.Attribute(DocX.w + "styleId").Value.Equals(value));
}
private static string BuildSwitchString(TableOfContentsSwitches switches, int lastIncludeLevel)
{
var allSwitches = Enum.GetValues(typeof (TableOfContentsSwitches)).Cast<TableOfContentsSwitches>();
var switchString = "TOC";
foreach (var s in allSwitches.Where(s => s != TableOfContentsSwitches.None && switches.HasFlag(s)))
{
switchString += " " + s.EnumDescription();
if (s == TableOfContentsSwitches.O)
{
switchString += string.Format(" '{0}-{1}'", 1, lastIncludeLevel);
}
}
return switchString;
}
}
}

+ 0
- 310
DocX/_BaseClasses.cs View File

@@ -1,310 +0,0 @@
using System;
using System.IO.Packaging;
using System.Linq;
using System.Xml.Linq;
namespace Novacode
{
/// <summary>
/// All DocX types are derived from DocXElement.
/// This class contains properties which every element of a DocX must contain.
/// </summary>
public abstract class DocXElement
{
internal PackagePart mainPart;
public PackagePart PackagePart { get { return mainPart; } set { mainPart = value; } }
/// <summary>
/// This is the actual Xml that gives this element substance.
/// For example, a Paragraphs Xml might look something like the following
/// <p>
/// <r>
/// <t>Hello World!</t>
/// </r>
/// </p>
/// </summary>
public XElement Xml { get; set; }
/// <summary>
/// This is a reference to the DocX object that this element belongs to.
/// Every DocX element is connected to a document.
/// </summary>
internal DocX Document { get; set; }
/// <summary>
/// Store both the document and xml so that they can be accessed by derived types.
/// </summary>
/// <param name="document">The document that this element belongs to.</param>
/// <param name="xml">The Xml that gives this element substance</param>
public DocXElement(DocX document, XElement xml)
{
this.Document = document;
this.Xml = xml;
}
}
/// <summary>
/// This class provides functions for inserting new DocXElements before or after the current DocXElement.
/// Only certain DocXElements can support these functions without creating invalid documents, at the moment these are Paragraphs and Table.
/// </summary>
public abstract class InsertBeforeOrAfter : DocXElement
{
public InsertBeforeOrAfter(DocX document, XElement xml) : base(document, xml) { }
public virtual void InsertPageBreakBeforeSelf()
{
XElement p = new XElement
(
XName.Get("p", DocX.w.NamespaceName),
new XElement
(
XName.Get("r", DocX.w.NamespaceName),
new XElement
(
XName.Get("br", DocX.w.NamespaceName),
new XAttribute(XName.Get("type", DocX.w.NamespaceName), "page")
)
)
);
Xml.AddBeforeSelf(p);
}
public virtual void InsertPageBreakAfterSelf()
{
XElement p = new XElement
(
XName.Get("p", DocX.w.NamespaceName),
new XElement
(
XName.Get("r", DocX.w.NamespaceName),
new XElement
(
XName.Get("br", DocX.w.NamespaceName),
new XAttribute(XName.Get("type", DocX.w.NamespaceName), "page")
)
)
);
Xml.AddAfterSelf(p);
}
public virtual Paragraph InsertParagraphBeforeSelf(Paragraph p)
{
Xml.AddBeforeSelf(p.Xml);
XElement newlyInserted = Xml.ElementsBeforeSelf().First();
p.Xml = newlyInserted;
return p;
}
public virtual Paragraph InsertParagraphAfterSelf(Paragraph p)
{
Xml.AddAfterSelf(p.Xml);
XElement newlyInserted = Xml.ElementsAfterSelf().First();
//Dmitchern
if (this as Paragraph != null)
{
return new Paragraph(Document, newlyInserted, (this as Paragraph).endIndex);
}
p.Xml = newlyInserted; //IMPORTANT: I think we have return new paragraph in any case, but I dont know what to put as startIndex parameter into Paragraph constructor
return p;
}
public virtual Paragraph InsertParagraphBeforeSelf(string text)
{
return InsertParagraphBeforeSelf(text, false, new Formatting());
}
public virtual Paragraph InsertParagraphAfterSelf(string text)
{
return InsertParagraphAfterSelf(text, false, new Formatting());
}
public virtual Paragraph InsertParagraphBeforeSelf(string text, bool trackChanges)
{
return InsertParagraphBeforeSelf(text, trackChanges, new Formatting());
}
public virtual Paragraph InsertParagraphAfterSelf(string text, bool trackChanges)
{
return InsertParagraphAfterSelf(text, trackChanges, new Formatting());
}
public virtual Paragraph InsertParagraphBeforeSelf(string text, bool trackChanges, Formatting formatting)
{
XElement newParagraph = new XElement
(
XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName)), HelperFunctions.FormatInput(text, formatting.Xml)
);
if (trackChanges)
newParagraph = Paragraph.CreateEdit(EditType.ins, DateTime.Now, newParagraph);
Xml.AddBeforeSelf(newParagraph);
XElement newlyInserted = Xml.ElementsBeforeSelf().Last();
return new Paragraph(Document, newlyInserted, -1);
}
public virtual Paragraph InsertParagraphAfterSelf(string text, bool trackChanges, Formatting formatting)
{
XElement newParagraph = new XElement
(
XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName)), HelperFunctions.FormatInput(text, formatting.Xml)
);
if (trackChanges)
newParagraph = Paragraph.CreateEdit(EditType.ins, DateTime.Now, newParagraph);
Xml.AddAfterSelf(newParagraph);
XElement newlyInserted = Xml.ElementsAfterSelf().First();
Paragraph p = new Paragraph(Document, newlyInserted, -1);
return p;
}
public virtual Table InsertTableAfterSelf(int rowCount, int columnCount)
{
XElement newTable = HelperFunctions.CreateTable(rowCount, columnCount);
Xml.AddAfterSelf(newTable);
XElement newlyInserted = Xml.ElementsAfterSelf().First();
return new Table(Document, newlyInserted) { mainPart = mainPart };
}
public virtual Table InsertTableAfterSelf(Table t)
{
Xml.AddAfterSelf(t.Xml);
XElement newlyInserted = Xml.ElementsAfterSelf().First();
//Dmitchern
return new Table(Document, newlyInserted) { mainPart = mainPart }; //return new table, dont affect parameter table
}
public virtual Table InsertTableBeforeSelf(int rowCount, int columnCount)
{
XElement newTable = HelperFunctions.CreateTable(rowCount, columnCount);
Xml.AddBeforeSelf(newTable);
XElement newlyInserted = Xml.ElementsBeforeSelf().Last();
return new Table(Document, newlyInserted) { mainPart = mainPart };
}
public virtual Table InsertTableBeforeSelf(Table t)
{
Xml.AddBeforeSelf(t.Xml);
XElement newlyInserted = Xml.ElementsBeforeSelf().Last();
//Dmitchern
return new Table(Document, newlyInserted) { mainPart=mainPart}; //return new table, dont affect parameter table
}
}
public static class XmlTemplateBases
{
#region TocXml
public const string TocXmlBase = @"<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='{0}'/>
</w:pPr>
<w:r>
<w:t>{1}</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='{2}'/>
</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'> {3} </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>
";
public const string TocHeadingStyleBase = @"<w:style w:type='paragraph' w:styleId='{0}' 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:rsid w:val='00E67AA6'/>
<w:pPr>
<w:outlineLvl w:val='9'/>
</w:pPr>
<w:rPr>
<w:lang w:eastAsia='nb-NO'/>
</w:rPr>
</w:style>
";
public const string TocElementStyleBase = @" <w:style w:type='paragraph' w:styleId='{0}' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
<w:name w:val='{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:ind w:left='440' />
</w:pPr>
</w:style>
";
public const string TocHyperLinkStyleBase = @" <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='Normal' />
<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>
";
#endregion
}
}

+ 0
- 97
DocX/_Extensions.cs View File

@@ -1,97 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Xml.Linq;
namespace Novacode
{
internal static class Extensions
{
internal static string ToHex(this Color source)
{
byte red = source.R;
byte green = source.G;
byte blue = source.B;
string redHex = red.ToString("X");
if (redHex.Length < 2)
redHex = "0" + redHex;
string blueHex = blue.ToString("X");
if (blueHex.Length < 2)
blueHex = "0" + blueHex;
string greenHex = green.ToString("X");
if (greenHex.Length < 2)
greenHex = "0" + greenHex;
return string.Format("{0}{1}{2}", redHex, greenHex, blueHex);
}
public static void Flatten(this XElement e, XName name, List<XElement> flat)
{
// Add this element (without its children) to the flat list.
XElement clone = CloneElement(e);
clone.Elements().Remove();
// Filter elements using XName.
if (clone.Name == name)
flat.Add(clone);
// Process the children.
if (e.HasElements)
foreach (XElement elem in e.Elements(name)) // Filter elements using XName
elem.Flatten(name, flat);
}
static XElement CloneElement(XElement element)
{
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n =>
{
XElement e = n as XElement;
if (e != null)
return CloneElement(e);
return n;
}
)
);
}
public static string GetAttribute(this XElement el, XName name, string defaultValue = "")
{
var attr = el.Attribute(name);
if (attr != null)
return attr.Value;
return defaultValue;
}
/// <summary>
/// Sets margin for all the pages in a Dox document in Inches. (Written by Shashwat Tripathi)
/// </summary>
/// <param name="document"></param>
/// <param name="top">Margin from the Top. Leave -1 for no change</param>
/// <param name="bottom">Margin from the Bottom. Leave -1 for no change</param>
/// <param name="right">Margin from the Right. Leave -1 for no change</param>
/// <param name="left">Margin from the Left. Leave -1 for no change</param>
public static void SetMargin(this DocX document, float top, float bottom, float right, float left)
{
XNamespace ab = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
var tempElement = document.PageLayout.Xml.Descendants(ab + "pgMar");
foreach (var item in tempElement)
{
if (left != -1)
item.SetAttributeValue(ab + "left", (1440 * left) / 1);
if (right != -1)
item.SetAttributeValue(ab + "right", (1440 * right) / 1);
if (top != -1)
item.SetAttributeValue(ab + "top", (1440 * top) / 1);
if (bottom != -1)
item.SetAttributeValue(ab + "bottom", (1440 * bottom) / 1);
}
}
}
}

+ 0
- 88
Documentation/Documentation.shfbproj View File

@@ -1,88 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<!-- The configuration and platform will be used to determine which
assemblies to include from solution and project documentation
sources -->
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{1eb1ee8f-9978-425b-a742-533dcceb4811}</ProjectGuid>
<SHFBSchemaVersion>2015.6.5.0</SHFBSchemaVersion>
<!-- AssemblyName, Name, and RootNamespace are not used by SHFB but Visual
Studio adds them anyway -->
<AssemblyName>Documentation</AssemblyName>
<RootNamespace>Documentation</RootNamespace>
<Name>Documentation</Name>
<!-- SHFB properties -->
<OutputPath>Help\</OutputPath>
<HtmlHelpName>Documentation</HtmlHelpName>
<Language>en-US</Language>
<HelpFileFormat>HtmlHelp1</HelpFileFormat>
<IndentHtml>False</IndentHtml>
<FrameworkVersion>.NET Framework 3.5</FrameworkVersion>
<KeepLogFile>True</KeepLogFile>
<DisableCodeBlockComponent>False</DisableCodeBlockComponent>
<CppCommentsFixup>False</CppCommentsFixup>
<CleanIntermediates>True</CleanIntermediates>
<SyntaxFilters>Standard</SyntaxFilters>
<SdkLinkTarget>Blank</SdkLinkTarget>
<RootNamespaceContainer>False</RootNamespaceContainer>
<PresentationStyle>VS2013</PresentationStyle>
<Preliminary>False</Preliminary>
<NamingMethod>Guid</NamingMethod>
<HelpTitle>DocX - A Sandcastle Documented Class Library</HelpTitle>
<FeedbackEMailLinkText>coffey.cathal%40gmail.com</FeedbackEMailLinkText>
<FeedbackEMailAddress>coffey.cathal%40gmail.com</FeedbackEMailAddress>
<ContentPlacement>AboveNamespaces</ContentPlacement>
<DocumentationSources>
<DocumentationSource sourceFile="..\DocX\DocX.csproj" />
</DocumentationSources>
<SccProjectName>SAK</SccProjectName>
<SccProvider>SAK</SccProvider>
<SccAuxPath>SAK</SccAuxPath>
<SccLocalPath>SAK</SccLocalPath>
<WorkingPath>%temp%\</WorkingPath>
<ApiFilter />
<ComponentConfigurations />
<HelpAttributes />
<NamespaceSummaries />
<PlugInConfigurations />
<BuildLogFile />
<HtmlHelp1xCompilerPath />
<HtmlHelp2xCompilerPath />
<SandcastlePath />
<ComponentPath />
<BuildAssemblerVerbosity>OnlyWarningsAndErrors</BuildAssemblerVerbosity>
<HelpFileVersion>1.0.0.0</HelpFileVersion>
<MaximumGroupParts>2</MaximumGroupParts>
<NamespaceGrouping>False</NamespaceGrouping>
</PropertyGroup>
<!-- There are no properties for these groups. AnyCPU needs to appear in
order for Visual Studio to perform the build. The others are optional
common platform types that may appear. -->
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|Win32' ">
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|Win32' ">
</PropertyGroup>
<ItemGroup>
<Folder Include="Help\" />
</ItemGroup>
<ItemGroup>
<None Include="Help\Documentation.chm" />
</ItemGroup>
<!-- Import the SHFB build targets -->
<Import Project="$(SHFBROOT)\SandcastleHelpFileBuilder.targets" />
</Project>

+ 0
- 10
Documentation/Documentation.shfbproj.vspscc View File

@@ -1,10 +0,0 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}

+ 0
- 97
Examples/Examples.csproj View File

@@ -1,97 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{F3022BB7-0E40-4C80-A495-37FEAF3671AB}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Examples</RootNamespace>
<AssemblyName>Examples</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<UseVSHostingProcess>true</UseVSHostingProcess>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<PlatformTarget>AnyCPU</PlatformTarget>
<OutputPath>bin\Debug\</OutputPath>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<PlatformTarget>AnyCPU</PlatformTarget>
<OutputPath>bin\Release\</OutputPath>
<Prefer32Bit>false</Prefer32Bit>
<Optimize>true</Optimize>
<UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RelativeDirectory.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="docs\DocumentWithBookmarks.docx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="docs\DocumentWithTemplateTable.docx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="docs\Input.docx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DocX\DocX.csproj">
<Project>{e863d072-aa8b-4108-b5f1-785241b37f67}</Project>
<Name>DocX</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

+ 0
- 10
Examples/Examples.csproj.vspscc View File

@@ -1,10 +0,0 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}

+ 111
- 1993
Examples/Program.cs
File diff suppressed because it is too large
View File


+ 15
- 23
Examples/Properties/AssemblyInfo.cs View File

@@ -1,36 +1,28 @@
using System.Reflection;
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Examples")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Examples")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyTitle( "Xceed Words for .NET - Examples" )]
[assembly: AssemblyDescription( "This assembly contains the Examples for Xceed Words for .NET." )]
[assembly: AssemblyCompany( "Xceed Software Inc." )]
[assembly: AssemblyProduct( "Xceed Words for .NET" )]
[assembly: AssemblyCopyright( "Copyright (C) Xceed Software Inc. 2009-2017" )]
[assembly: AssemblyCulture( "" )]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b18a3992-244e-430f-8ba2-cc3dd17971e6")]
#pragma warning disable 1699
[assembly: AssemblyDelaySign( false )]
[assembly: AssemblyKeyFile( @"..\..\..\sn.snk" )]
[assembly: AssemblyKeyName( "" )]
#pragma warning restore 1699
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

+ 0
- 73
Examples/RelativeDirectory.cs View File

@@ -1,73 +0,0 @@
using System;
using System.IO;
namespace Examples
{
class RelativeDirectory
{
// Author D. Bolton see http://cplus.about.com (c) 2010
private DirectoryInfo _dirInfo;
public string Dir
{
get
{
return _dirInfo.Name;
}
}
public string Path
{
get { return _dirInfo.FullName; }
set
{
try
{
DirectoryInfo newDir = new DirectoryInfo(value);
_dirInfo = newDir;
}
catch
{
// silent
}
}
}
public RelativeDirectory()
{
_dirInfo = new DirectoryInfo(Environment.CurrentDirectory);
}
public RelativeDirectory(string absoluteDir)
{
_dirInfo = new DirectoryInfo(absoluteDir);
}
public Boolean Up(int numLevels)
{
for (int i = 0; i < numLevels; i++)
{
DirectoryInfo tempDir = _dirInfo.Parent;
if (tempDir != null)
_dirInfo = tempDir;
else
return false;
}
return true;
}
public Boolean Up()
{
return Up(1);
}
public Boolean Down(string match)
{
DirectoryInfo[] dirs = _dirInfo.GetDirectories(match + '*');
_dirInfo = dirs[0];
return true;
}
}
}

+ 115
- 0
Examples/Samples/Bookmark/BookmarkSample.cs View File

@@ -0,0 +1,115 @@
/***************************************************************************************

DocX – DocX is the community edition of Xceed Words for .NET

Copyright (C) 2009-2017 Xceed Software Inc.

This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license

For more features and fast professional support,
pick up Xceed Words for .NET at https://xceed.com/xceed-words-for-net/

*************************************************************************************/
using System;
using System.IO;
using System.Linq;

namespace Xceed.Words.NET.Examples
{
public class BookmarkSample
{
#region Private Members

private const string BookmarkSampleResourcesDirectory = Program.SampleDirectory + @"Bookmark\Resources\";
private const string BookmarkSampleOutputDirectory = Program.SampleDirectory + @"Bookmark\Output\";

#endregion

#region Constructors

static BookmarkSample()
{
if( !Directory.Exists( BookmarkSample.BookmarkSampleOutputDirectory ) )
{
Directory.CreateDirectory( BookmarkSample.BookmarkSampleOutputDirectory );
}
}

#endregion

#region Public Methods

/// <summary>
/// Insert a bookmark in a document and a paragraph(and replace the displayed bookmark).
/// </summary>
public static void InsertBookmarks()
{
Console.WriteLine( "\tInsertBookmarks()" );

// Create a document
using( DocX document = DocX.Create( BookmarkSample.BookmarkSampleOutputDirectory + @"InsertBookmarks.docx" ) )
{
// Add a title
document.InsertParagraph( "Insert Bookmarks" ).FontSize( 15d ).SpacingAfter( 40d ).Alignment = Alignment.center;

// Insert a bookmark in the document.
document.InsertBookmark( "Bookmark1" );

// Add a paragraph
var p = document.InsertParagraph( "This document contains a bookmark named \"" );
p.Append( document.Bookmarks.First().Name );
p.Append( "\" just before this line." );
p.SpacingAfter( 50d );

var _bookmarkName = "Bookmark2";
var _displayedBookmarkName = "special";

// Add another paragraph.
var p2 = document.InsertParagraph( "This paragraph contains a " );
// Add a bookmark into the paragraph.
p2.AppendBookmark( _bookmarkName );
p2.Append( " bookmark named \"" );
p2.Append( document.Bookmarks.Last().Name );
p2.Append( "\" but displayed as \"" + _displayedBookmarkName + "\"." );

// Set a string to be displayed as the Bookmark in the second paragraph.
p2.InsertAtBookmark( _displayedBookmarkName, _bookmarkName );

document.Save();
Console.WriteLine( "\tCreated: InsertBookmarks.docx\n" );
}
}

/// <summary>
/// Load a document with bookmarks and replace the bookmark's text.
/// </summary>
public static void ReplaceText()
{
Console.WriteLine( "\tReplaceBookmarkText()" );

// Load a document
using( DocX document = DocX.Load( BookmarkSample.BookmarkSampleResourcesDirectory + @"DocumentWithBookmarks.docx" ) )
{
// Get the regular bookmark from the document and replace its Text.
var regularBookmark = document.Bookmarks[ "regBookmark" ];
if( regularBookmark != null )
{
regularBookmark.SetText( "Regular Bookmark has been changed" );
}

// Get the formatted bookmark from the document and replace its Text.
var formattedBookmark = document.Bookmarks[ "formattedBookmark" ];
if( formattedBookmark != null )
{
formattedBookmark.SetText( "Formatted Bookmark has been changed" );
}

document.SaveAs( BookmarkSample.BookmarkSampleOutputDirectory + @"ReplaceBookmarkText.docx" );
Console.WriteLine( "\tCreated: ReplaceBookmarkText.docx\n" );
}
}

#endregion
}
}

BIN
Examples/Samples/Bookmark/Resources/DocumentWithBookmarks.docx View File


+ 61
- 0
Examples/Samples/Chart/ChartData.cs View File

@@ -0,0 +1,61 @@
/***************************************************************************************

DocX – DocX is the community edition of Xceed Words for .NET

Copyright (C) 2009-2017 Xceed Software Inc.

This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license

For more features and fast professional support,
pick up Xceed Words for .NET at https://xceed.com/xceed-words-for-net/

*************************************************************************************/
using System.Collections.Generic;

namespace Xceed.Words.NET.Examples
{
internal class ChartData
{
public string Category
{
get;
set;
}
public double Expenses
{
get;
set;
}

public static List<ChartData> CreateCanadaExpenses()
{
var canada = new List<ChartData>();
canada.Add( new ChartData() { Category = "Food", Expenses = 100 } );
canada.Add( new ChartData() { Category = "Housing", Expenses = 120 } );
canada.Add( new ChartData() { Category = "Transportation", Expenses = 140 } );
canada.Add( new ChartData() { Category = "Health Care", Expenses = 150 } );
return canada;
}

public static List<ChartData> CreateUSAExpenses()
{
var usa = new List<ChartData>();
usa.Add( new ChartData() { Category = "Food", Expenses = 200 } );
usa.Add( new ChartData() { Category = "Housing", Expenses = 150 } );
usa.Add( new ChartData() { Category = "Transportation", Expenses = 110 } );
usa.Add( new ChartData() { Category = "Health Care", Expenses = 100 } );
return usa;
}

public static List<ChartData> CreateBrazilExpenses()
{
var brazil = new List<ChartData>();
brazil.Add( new ChartData() { Category = "Food", Expenses = 125 } );
brazil.Add( new ChartData() { Category = "Housing", Expenses = 80 } );
brazil.Add( new ChartData() { Category = "Transportation", Expenses = 110 } );
brazil.Add( new ChartData() { Category = "Health Care", Expenses = 60 } );
return brazil;
}
}
}

+ 207
- 0
Examples/Samples/Chart/ChartSample.cs View File

@@ -0,0 +1,207 @@
/***************************************************************************************

DocX – DocX is the community edition of Xceed Words for .NET

Copyright (C) 2009-2017 Xceed Software Inc.

This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license

For more features and fast professional support,
pick up Xceed Words for .NET at https://xceed.com/xceed-words-for-net/

*************************************************************************************/
using System;
using System.Drawing;
using System.IO;

namespace Xceed.Words.NET.Examples
{
public class ChartSample
{
#region Private Members

private const string ChartSampleOutputDirectory = Program.SampleDirectory + @"Chart\Output\";

#endregion

#region Constructors

static ChartSample()
{
if( !Directory.Exists( ChartSample.ChartSampleOutputDirectory ) )
{
Directory.CreateDirectory( ChartSample.ChartSampleOutputDirectory );
}
}

#endregion

#region Public Methods

/// <summary>
/// Add a Bar chart to a document.
/// </summary>
public static void BarChart()
{
Console.WriteLine( "\tBarChart()" );

// Creates a document
using( DocX document = DocX.Create( ChartSample.ChartSampleOutputDirectory + @"BarChart.docx" ) )
{
// Add a title
document.InsertParagraph( "Bar Chart" ).FontSize( 15d ).SpacingAfter( 50d ).Alignment = Alignment.center;

// Create a bar chart.
var c = new BarChart();
c.AddLegend( ChartLegendPosition.Left, false );
c.BarDirection = BarDirection.Bar;
c.BarGrouping = BarGrouping.Standard;
c.GapWidth = 200;

// Create the data.
var canada = ChartData.CreateCanadaExpenses();
var usa = ChartData.CreateUSAExpenses();
var brazil = ChartData.CreateBrazilExpenses();

// Create and add series
var s1 = new Series( "Brazil" );
s1.Color = Color.GreenYellow;
s1.Bind( brazil, "Category", "Expenses" );
c.AddSeries( s1 );

var s2 = new Series( "USA" );
s2.Color = Color.LightBlue;
s2.Bind( usa, "Category", "Expenses" );
c.AddSeries( s2 );

var s3 = new Series( "Canada" );
s3.Color = Color.Gray;
s3.Bind( canada, "Category", "Expenses" );
c.AddSeries( s3 );

// Insert the chart into the document.
document.InsertParagraph( "Expenses(M$) for selected categories per country" ).FontSize( 15 ).SpacingAfter( 10d );
document.InsertChart( c );

document.Save();
Console.WriteLine( "\tCreated: BarChart.docx\n" );
}
}

/// <summary>
/// Add a Line chart to a document.
/// </summary>
public static void LineChart()
{
Console.WriteLine( "\tLineChartt()" );

// Creates a document
using( DocX document = DocX.Create( ChartSample.ChartSampleOutputDirectory + @"LineChart.docx" ) )
{
// Add a title
document.InsertParagraph( "Line Chart" ).FontSize( 15d ).SpacingAfter( 50d ).Alignment = Alignment.center;

// Create a line chart.
var c = new LineChart();
c.AddLegend( ChartLegendPosition.Left, false );

// Create the data.
var canada = ChartData.CreateCanadaExpenses();
var usa = ChartData.CreateUSAExpenses();
var brazil = ChartData.CreateBrazilExpenses();

// Create and add series
var s1 = new Series( "Brazil" );
s1.Bind( brazil, "Category", "Expenses" );
c.AddSeries( s1 );

var s2 = new Series( "USA" );
s2.Bind( usa, "Category", "Expenses" );
c.AddSeries( s2 );

var s3 = new Series( "Canada" );
s3.Bind( canada, "Category", "Expenses" );
c.AddSeries( s3 );

// Insert chart into document
document.InsertParagraph( "Expenses(M$) for selected categories per country" ).FontSize( 15 ).SpacingAfter( 10d );
document.InsertChart( c );

document.Save();
Console.WriteLine( "\tCreated: LineChart.docx\n" );
}
}

/// <summary>
/// Add a Pie chart to a document.
/// </summary>
public static void PieChart()
{
Console.WriteLine( "\tPieChart()" );

// Creates a document
using( DocX document = DocX.Create( ChartSample.ChartSampleOutputDirectory + @"PieChart.docx" ) )
{
// Add a title
document.InsertParagraph( "Pie Chart" ).FontSize( 15d ).SpacingAfter( 50d ).Alignment = Alignment.center;

// Create a pie chart.
var c = new PieChart();
c.AddLegend( ChartLegendPosition.Left, false );

// Create the data.
var brazil = ChartData.CreateBrazilExpenses();

// Create and add series
var s1 = new Series( "Canada" );
s1.Bind( brazil, "Category", "Expenses" );
c.AddSeries( s1 );

// Insert chart into document
document.InsertParagraph( "Expenses(M$) for selected categories of Canada" ).FontSize( 15 ).SpacingAfter( 10d );
document.InsertChart( c );

document.Save();
Console.WriteLine( "\tCreated: PieChart.docx\n" );
}
}

/// <summary>
/// Add a 3D bar chart to a document.
/// </summary>
///
public static void Chart3D()
{
Console.WriteLine( "\tChart3D)" );

// Creates a document
using( DocX document = DocX.Create( ChartSample.ChartSampleOutputDirectory + @"3DChart.docx" ) )
{
// Add a title
document.InsertParagraph( "3D Chart" ).FontSize( 15d ).SpacingAfter( 50d ).Alignment = Alignment.center;

// Create a 3D Bar chart.
var c = new BarChart();
c.View3D = true;

// Create the data.
var brazil = ChartData.CreateBrazilExpenses();

// Create and add series
var s1 = new Series( "Brazil" );
s1.Color = Color.GreenYellow;
s1.Bind( brazil, "Category", "Expenses" );
c.AddSeries( s1 );

// Insert chart into document
document.InsertParagraph( "Expenses(M$) for selected categories of Brazil" ).FontSize( 15 ).SpacingAfter( 10d );
document.InsertChart( c );

document.Save();
Console.WriteLine( "\tCreated: 3DChart.docx\n" );
}
}
#endregion
}
}

+ 178
- 0
Examples/Samples/Document/DocumentSample.cs View File

@@ -0,0 +1,178 @@
/***************************************************************************************

DocX – DocX is the community edition of Xceed Words for .NET

Copyright (C) 2009-2017 Xceed Software Inc.

This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license

For more features and fast professional support,
pick up Xceed Words for .NET at https://xceed.com/xceed-words-for-net/

*************************************************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace Xceed.Words.NET.Examples
{
public class DocumentSample
{
#region Private Members

private static Dictionary<string, string> _replacePatterns = new Dictionary<string, string>()
{
{ "OPPONENT", "Pittsburgh Penguins" },
{ "GAME_TIME", "19h30" },
{ "GAME_NUMBER", "161" },
{ "DATE", "October 18 2016" },
};

private const string DocumentSampleResourcesDirectory = Program.SampleDirectory + @"Document\Resources\";
private const string DocumentSampleOutputDirectory = Program.SampleDirectory + @"Document\Output\";

#endregion

#region Constructors

static DocumentSample()
{
if( !Directory.Exists( DocumentSample.DocumentSampleOutputDirectory ) )
{
Directory.CreateDirectory( DocumentSample.DocumentSampleOutputDirectory );
}
}

#endregion

#region Public Methods

/// <summary>
/// Load a document and replace texts following a replace pattern.
/// </summary>
public static void ReplaceText()
{
Console.WriteLine( "\tReplaceText()" );

// Load a document.
using( DocX document = DocX.Load( DocumentSample.DocumentSampleResourcesDirectory + @"ReplaceText.docx" ) )
{
// Check if all the replace patterns are used in the loaded document.
if( document.FindUniqueByPattern( @"<[\w \=]{4,}>", RegexOptions.IgnoreCase ).Count == _replacePatterns.Count )
{
// Do the replacement
for( int i = 0; i < _replacePatterns.Count; ++i )
{
document.ReplaceText( "<(.*?)>", DocumentSample.ReplaceFunc, false, RegexOptions.IgnoreCase, null, new Formatting() );
}

// Save this document to disk.
document.SaveAs( DocumentSample.DocumentSampleOutputDirectory + @"ReplacedText.docx" );
Console.WriteLine( "\tCreated: ReplacedText.docx\n" );
}
}
}

/// <summary>
/// Add custom properties to a document.
/// </summary>
public static void AddCustomProperties()
{
Console.WriteLine( "\tAddCustomProperties()" );

// Create a new document.
using( DocX document = DocX.Create( DocumentSample.DocumentSampleOutputDirectory + @"AddCustomProperties.docx" ) )
{
// Add a title
document.InsertParagraph( "Adding Custom Properties to a document" ).FontSize( 15d ).SpacingAfter( 50d ).Alignment = Alignment.center;

//Add custom properties to document.
document.AddCustomProperty( new CustomProperty( "CompanyName", "Xceed Software inc." ) );
document.AddCustomProperty( new CustomProperty( "Product", "Xceed Words for .NET" ) );
document.AddCustomProperty( new CustomProperty( "Address", "10 Boul. de Mortagne" ) );
document.AddCustomProperty( new CustomProperty( "Date", DateTime.Now ) );

// Add a paragraph displaying the number of custom properties.
var p = document.InsertParagraph( "This document contains " ).Append( document.CustomProperties.Count.ToString() ).Append(" Custom Properties :");
p.SpacingAfter( 30 );

// Display each propertie's name and value.
foreach( var prop in document.CustomProperties )
{
document.InsertParagraph( prop.Value.Name ).Append( " = " ).Append( prop.Value.Value.ToString() ).AppendLine();
}

// Save this document to disk.
document.Save();
Console.WriteLine( "\tCreated: AddCustomProperties.docx\n" );
}
}

/// <summary>
/// Add a template to a document.
/// </summary>
public static void ApplyTemplate()
{
Console.WriteLine( "\tApplyTemplate()" );

// Create a new document.
using( DocX document = DocX.Create( DocumentSample.DocumentSampleOutputDirectory + @"ApplyTemplate.docx" ) )
{
// The path to a template document,
var templatePath = DocumentSample.DocumentSampleResourcesDirectory + @"Template.docx";

// Apply a template to the document based on a path.
document.ApplyTemplate( templatePath );

// Add a paragraph at the end of the template.
document.InsertParagraph( "This paragraph is not part of the template." ).FontSize( 15d ).UnderlineStyle(UnderlineStyle.singleLine).SpacingBefore(50d);

// Save this document to disk.
document.Save();
Console.WriteLine( "\tCreated: ApplyTemplate.docx\n" );
}
}

/// <summary>
/// Insert a document at the end of another document.
/// </summary>
public static void AppendDocument()
{
Console.WriteLine( "\tAppendDocument()" );

// Load the first document.
using( DocX document1 = DocX.Load( DocumentSample.DocumentSampleResourcesDirectory + @"First.docx" ) )
{
// Load the second document.
using( DocX document2 = DocX.Load( DocumentSample.DocumentSampleResourcesDirectory + @"Second.docx" ) )
{
// Insert a document at the end of another document.
// When true, document is added at the end. When false, document is added at beginning.
document1.InsertDocument( document2, true );

// Save this document to disk.
document1.SaveAs( DocumentSample.DocumentSampleOutputDirectory + @"AppendDocument.docx" );
Console.WriteLine( "\tCreated: AppendDocument.docx\n" );
}
}
}

#endregion

#region Private Methods

private static string ReplaceFunc( string findStr )
{
if( _replacePatterns.ContainsKey( findStr ) )
{
return _replacePatterns[ findStr ];
}
return findStr;
}

#endregion
}
}

BIN
Examples/Samples/Document/Resources/First.docx View File


BIN
Examples/Samples/Document/Resources/ReplaceText.docx View File


BIN
Examples/Samples/Document/Resources/Second.docx View File


BIN
Examples/Samples/Document/Resources/Template.docx View File


+ 71
- 0
Examples/Samples/Equation/EquationSample.cs View File

@@ -0,0 +1,71 @@
/***************************************************************************************

DocX – DocX is the community edition of Xceed Words for .NET

Copyright (C) 2009-2017 Xceed Software Inc.

This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license

For more features and fast professional support,
pick up Xceed Words for .NET at https://xceed.com/xceed-words-for-net/

*************************************************************************************/

using System;
using System.Drawing;
using System.IO;

namespace Xceed.Words.NET.Examples
{
public class EquationSample
{
#region Private Members

private const string EquationSampleOutputDirectory = Program.SampleDirectory + @"Equation\Output\";

#endregion

#region Constructors

static EquationSample()
{
if( !Directory.Exists( EquationSample.EquationSampleOutputDirectory ) )
{
Directory.CreateDirectory( EquationSample.EquationSampleOutputDirectory );
}
}

#endregion

#region Public Methods

/// <summary>
/// Create a document and add Equations in it.
/// </summary>
public static void InsertEquation()
{
Console.WriteLine( "\tEquationSample()" );

// Create a document.
using( DocX document = DocX.Create( EquationSample.EquationSampleOutputDirectory + @"EquationSample.docx" ) )
{
// Add a title
document.InsertParagraph( "Inserting Equations" ).FontSize( 15d ).SpacingAfter( 50d ).Alignment = Alignment.center;

document.InsertParagraph( "A Linear equation : " );
// Insert first Equation in this document.
document.InsertEquation( "y = mx + b" ).SpacingAfter( 30d );

document.InsertParagraph( "A Quadratic equation : " );
// Insert second Equation in this document and add formatting.
document.InsertEquation( "x = ( -b \u00B1 \u221A(b\u00B2 - 4ac))/2a" ).FontSize( 18 ).Color( Color.Blue );

document.Save();
Console.WriteLine( "\tCreated: EquationSample.docx\n" );
}
}

#endregion
}
}

+ 0
- 0
Examples/Samples/HeaderFooter/HeaderFooterSample.cs View File


Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save