├── .github
├── dependabot.yml
└── workflows
│ ├── CI.yml
│ └── Official.yml
├── .gitignore
├── AssemblyShader.sln
├── Directory.Build.props
├── Directory.Build.rsp
├── Directory.Build.targets
├── Directory.Packages.props
├── LICENSE
├── NuGet.config
├── README.md
├── build
├── PackageIcon.png
├── UnitTest.runsettings
└── key.snk
├── src
├── AssemblyShader.UnitTests
│ ├── AssemblyShader.UnitTests.csproj
│ ├── GetAssembliesToShadeTests.cs
│ ├── MockAssemblyInformationReader.cs
│ ├── MockInternalsVisibleToReader.cs
│ ├── MockNuGetProjectAssetsFileLoader.cs
│ ├── MockPackageAssemblyResolver.cs
│ ├── NuGetProjectAssetsFileLoaderTests.cs
│ ├── StringStream.cs
│ └── TestBase.cs
├── AssemblyShader
│ ├── AssemblyInformation.cs
│ ├── AssemblyInformationReader.cs
│ ├── AssemblyNameCache.cs
│ ├── AssemblyReference.cs
│ ├── AssemblyReferencesByAssemblyName.cs
│ ├── AssemblyShader.csproj
│ ├── AssemblyToRename.cs
│ ├── DotNetAssemblyResolver.cs
│ ├── ExtensionMethods.cs
│ ├── FileSystemInfoFullNameEqualityComparer.cs
│ ├── FriendAssembliesByInternalsVisibleTo.cs
│ ├── IAssemblyInformationReader.cs
│ ├── IInternalsVisibleToReader.cs
│ ├── INuGetProjectAssetsFileLoader.cs
│ ├── IPackageAssemblyResolver.cs
│ ├── InternalsVisibleToReader.cs
│ ├── ItemMetadataNames.cs
│ ├── NuGetProjectAssetsFile.cs
│ ├── NuGetProjectAssetsFileLoader.cs
│ ├── NuGetProjectAssetsFileSection.cs
│ ├── PackageAssembly.cs
│ ├── PackageAssemblyResolver.cs
│ ├── PackageIdentity.cs
│ ├── README.md
│ ├── Strings.Designer.cs
│ ├── Strings.resx
│ ├── StrongNameKeyPair.cs
│ ├── Tasks
│ │ ├── GetAssembliesToShade.cs
│ │ └── ShadeAssemblies.cs
│ └── build
│ │ ├── AssemblyShader.Common.targets
│ │ ├── AssemblyShader.targets
│ │ └── shaded.snk
└── GlobalSuppressions.cs
├── stylecop.json
├── version.json
└── xunit.runner.json
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 |
2 | # To get started with Dependabot version updates, you'll need to specify which
3 | # package ecosystems to update and where the package manifests are located.
4 | # Please see the documentation for all configuration options:
5 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
6 |
7 | version: 2
8 | updates:
9 | - package-ecosystem: "nuget" # See documentation for possible values
10 | directory: "/" # Location of package manifests
11 | schedule:
12 | interval: "monthly"
13 | assignees:
14 | - "jeffkl"
15 | labels:
16 | - "maintenance"
17 |
18 | - package-ecosystem: "github-actions"
19 | directory: "/"
20 | schedule:
21 | interval: "weekly"
22 |
23 | - package-ecosystem: "github-actions"
24 | directory: "/"
25 | schedule:
26 | interval: "weekly"
--------------------------------------------------------------------------------
/.github/workflows/CI.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | workflow_dispatch:
5 | push:
6 | branches:
7 | - main
8 | - rel/*
9 | pull_request:
10 | branches:
11 | - main
12 | - rel/*
13 |
14 | env:
15 | ArtifactsDirectoryName: 'artifacts'
16 | TestResultsDirectoryName: 'coverage'
17 | CommonTestArguments: '--no-restore --no-build --logger trx /noautorsp'
18 | BuildConfiguration: 'Debug'
19 | BuildPlatform: 'Any CPU'
20 | ContinuousIntegrationBuild: 'true'
21 |
22 | jobs:
23 | BuildAndTest:
24 | strategy:
25 | matrix:
26 | os: [windows-latest, ubuntu-latest, macos-latest]
27 | include:
28 | - os: windows-latest
29 | name: Windows
30 | testarguments: ''
31 | - os: ubuntu-latest
32 | name: Linux
33 | testarguments: '--collect:"XPlat Code Coverage"'
34 | - os: macos-latest
35 | name: MacOS
36 | testarguments: ''
37 | fail-fast: false
38 |
39 | name: Build and Test (${{ matrix.name }})
40 | runs-on: ${{ matrix.os }}
41 |
42 | steps:
43 | - name: Checkout
44 | uses: actions/checkout@v4
45 | with:
46 | fetch-depth: 0
47 |
48 | - name: Install .NET SDK 8.x and 9.x
49 | uses: actions/setup-dotnet@v4
50 | with:
51 | dotnet-version: |
52 | 8.x
53 | 9.x
54 |
55 | - name: Build Solution
56 | run: dotnet build "/Property:Platform=${{ env.BuildPlatform }};Configuration=${{ env.BuildConfiguration }}" "/BinaryLogger:${{ env.ArtifactsDirectoryName }}/build.binlog"
57 |
58 | - name: Run Unit Tests (.NET Framework)
59 | if: ${{ matrix.name == 'Windows' }}
60 | run: dotnet test ${{ env.CommonTestArguments }} ${{ matrix.TestArguments}} --framework net472 "/Property:Platform=${{ env.BuildPlatform }};Configuration=${{ env.BuildConfiguration }}" "/BinaryLogger:${{ env.ArtifactsDirectoryName }}/test-net472.binlog"
61 |
62 | - name: Run Unit Tests (.NET 8)
63 | run: dotnet test ${{ env.CommonTestArguments }} ${{ matrix.TestArguments}} --framework net8.0 "/Property:Platform=${{ env.BuildPlatform }};Configuration=${{ env.BuildConfiguration }}" "/BinaryLogger:${{ env.ArtifactsDirectoryName }}/test-net8.0.binlog"
64 |
65 | - name: Run Unit Tests (.NET 9)
66 | run: dotnet test ${{ env.CommonTestArguments }} ${{ matrix.TestArguments}} --framework net9.0 "/Property:Platform=${{ env.BuildPlatform }};Configuration=${{ env.BuildConfiguration }}" "/BinaryLogger:${{ env.ArtifactsDirectoryName }}/test-net9.0.binlog"
67 |
68 | - name: Upload Test Results
69 | uses: actions/upload-artifact@v4
70 | if: success() || failure()
71 | with:
72 | name: test-results-${{ matrix.name }}
73 | path: '**/TestResults/*.trx'
74 | if-no-files-found: error
75 |
76 | - name: Upload Artifacts
77 | uses: actions/upload-artifact@v4
78 | if: success() || failure()
79 | with:
80 | name: ${{ env.ArtifactsDirectoryName }}-${{ matrix.name }}
81 | path: ${{ env.ArtifactsDirectoryName }}
--------------------------------------------------------------------------------
/.github/workflows/Official.yml:
--------------------------------------------------------------------------------
1 | name: Official Build
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | - rel/*
8 | tags:
9 | - v*.*.*
10 |
11 | env:
12 | ArtifactsDirectoryName: 'artifacts'
13 | BuildConfiguration: 'Release'
14 | BuildPlatform: 'Any CPU'
15 | ContinuousIntegrationBuild: 'true'
16 | jobs:
17 | build:
18 | runs-on: windows-latest
19 | environment: Production
20 |
21 | steps:
22 | - name: Checkout
23 | uses: actions/checkout@v4
24 | with:
25 | fetch-depth: 0
26 |
27 | - name: Install .NET SDK 9.x
28 | uses: actions/setup-dotnet@v4
29 | with:
30 | dotnet-version: |
31 | 9.x
32 | dotnet-quality: preview
33 |
34 | - name: Build Solution
35 | run: dotnet build "/Property:Platform=${{ env.BuildPlatform }};Configuration=${{ env.BuildConfiguration }}" "/BinaryLogger:${{ env.ArtifactsDirectoryName }}\build.binlog"
36 |
37 | - name: Upload Artifacts
38 | uses: actions/upload-artifact@v4
39 | if: success() || failure()
40 | with:
41 | name: ${{ env.ArtifactsDirectoryName }}
42 | path: ${{ env.ArtifactsDirectoryName }}
43 |
44 | - name: Push Packages
45 | run: dotnet nuget push --skip-duplicate --api-key ${{ secrets.NuGetApiKey }} ${{ env.ArtifactsDirectoryName }}\**\*.nupkg
46 | if: ${{ startsWith(github.ref, 'refs/tags/v') }}
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | *.sln.iml
399 |
--------------------------------------------------------------------------------
/AssemblyShader.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.9.34223.224
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AssemblyShader", "src\AssemblyShader\AssemblyShader.csproj", "{CF56B79A-82DD-4131-A5D6-AC053D171939}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{061C346E-A4F7-4FD6-937B-ECF4E32E8A55}"
9 | ProjectSection(SolutionItems) = preProject
10 | Directory.Build.props = Directory.Build.props
11 | Directory.Build.targets = Directory.Build.targets
12 | Directory.Packages.props = Directory.Packages.props
13 | LICENSE = LICENSE
14 | README.md = README.md
15 | stylecop.json = stylecop.json
16 | build\UnitTest.runsettings = build\UnitTest.runsettings
17 | version.json = version.json
18 | EndProjectSection
19 | EndProject
20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AssemblyShader.UnitTests", "src\AssemblyShader.UnitTests\AssemblyShader.UnitTests.csproj", "{987AA0D8-2F97-4306-8907-08C70F003C97}"
21 | EndProject
22 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{891E0B0B-602F-45D7-8D76-13D78FDA43E1}"
23 | ProjectSection(SolutionItems) = preProject
24 | .github\workflows\CI.yml = .github\workflows\CI.yml
25 | .github\dependabot.yml = .github\dependabot.yml
26 | .github\workflows\Official.yml = .github\workflows\Official.yml
27 | EndProjectSection
28 | EndProject
29 | Global
30 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
31 | Debug|Any CPU = Debug|Any CPU
32 | Release|Any CPU = Release|Any CPU
33 | EndGlobalSection
34 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
35 | {CF56B79A-82DD-4131-A5D6-AC053D171939}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
36 | {CF56B79A-82DD-4131-A5D6-AC053D171939}.Debug|Any CPU.Build.0 = Debug|Any CPU
37 | {CF56B79A-82DD-4131-A5D6-AC053D171939}.Release|Any CPU.ActiveCfg = Release|Any CPU
38 | {CF56B79A-82DD-4131-A5D6-AC053D171939}.Release|Any CPU.Build.0 = Release|Any CPU
39 | {987AA0D8-2F97-4306-8907-08C70F003C97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
40 | {987AA0D8-2F97-4306-8907-08C70F003C97}.Debug|Any CPU.Build.0 = Debug|Any CPU
41 | {987AA0D8-2F97-4306-8907-08C70F003C97}.Release|Any CPU.ActiveCfg = Release|Any CPU
42 | {987AA0D8-2F97-4306-8907-08C70F003C97}.Release|Any CPU.Build.0 = Release|Any CPU
43 | EndGlobalSection
44 | GlobalSection(SolutionProperties) = preSolution
45 | HideSolutionNode = FALSE
46 | EndGlobalSection
47 | GlobalSection(ExtensibilityGlobals) = postSolution
48 | SolutionGuid = {D3CD8A52-A9AF-4064-A7FD-92FC1C4D69A1}
49 | EndGlobalSection
50 | EndGlobal
51 |
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | false
4 | false
5 | latest
6 | enable
7 | true
8 |
9 |
--------------------------------------------------------------------------------
/Directory.Build.rsp:
--------------------------------------------------------------------------------
1 | /Restore
2 | /ConsoleLoggerParameters:Verbosity=Minimal;Summary;ForceNoAlign
3 | /TerminalLogger:off
4 | /MaxCPUCount
5 | /Interactive
--------------------------------------------------------------------------------
/Directory.Build.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 | jeffkl
4 | jeffkl
5 | © All rights reserved.
6 | https://github.com/jeffkl/AssemblyShader
7 | README.md
8 | PackageIcon.png
9 | $(MSBuildThisFileDirectory)build\$(PackageIcon)
10 | https://github.com/jeffkl/AssemblyShader
11 | MIT
12 |
13 |
14 |
15 | true
16 | $(MSBuildThisFileDirectory)build\key.snk
17 |
18 | $(MSBuildThisFileDirectory)build\UnitTest.runsettings
19 |
20 |
21 |
22 |
23 |
25 |
26 |
27 |
28 |
29 |
30 |
33 |
37 |
38 |
--------------------------------------------------------------------------------
/Directory.Packages.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | true
4 | 17.13.9
5 | 6.13.2
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Jeff Kluge
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/NuGet.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # .NET Assembly Shader
2 | A .NET assembly shader for allowing .NET apps to load multiple versions of the same assembly.
3 |
4 | ## Shading Transitive Dependencies
5 | This package includes build logic to rename assemblies in your dependency graph that would otherwise be unified by the .NET SDK. Consider the following project's dependency graph:
6 |
7 | ```xml
8 |
9 |
10 |
11 |
12 |
13 |
14 | ```
15 |
16 | When `PackageA` and `PackageB` are restored, `PackageZ` version `2.0.0` will be used since it is the highest resolved version in the dependency graph. At runtime, `PackageA` will be forced to use `PackageZ` version `2.0.0`
17 | even if it was built and tested against `PackageZ` version `1.0.0`. If there have been any breaking runtime changes in `PackageZ`, `PackageA` could fail at runtime. Since only one version of `PackageZ` can exist in the application
18 | directory, it can be difficult to workaround the issue.
19 |
20 | On .NET Framework, you can place `PackageZ.dll` version `1.0.0.0` into a subfolder of the application directory and use assembly binding information in the `App.config` to tell the runtime where to find it. This will only work
21 | if the assembly is strong name signed however, since the .NET assembly loader can only load different versions of the same assembly side-by-side if they are strong named signed.
22 |
23 | On .NET Core, there is no way to work around this issue. The .NET assembly loader will always load the highest version of an assembly. The only path forward is to recompile `PackageA` against `PackageZ` version `2.0.0.0`
24 | which is not always possible.
25 |
26 | Assembly shading provides an escape hatch for the above example. It renames the `PackageZ` version `1.0.0` assembly so it can exist in the same directory as `PackageZ` version `2.0.0` and updates any assemblies that reference it.
27 |
28 | ```xml
29 |
30 |
31 |
32 |
33 |
34 |
35 | ```
36 |
37 | As the project is built, the package shader logic finds the assemblies in `PackageZ` version `1.0.0` and renames them. The renamed assembly is then copied to the application output directory.
38 |
39 | Now the output folder has both `PackageZ.dll` which is version `2.0.0.0` and `PackageZ.1.0.0.0.dll`.
40 |
41 | 
42 |
43 | `PackageA.dll` was also updated to reference `PackageZ.1.0.0.0.dll` instead of `PackageZ.dll`.
44 |
45 | 
46 |
47 | ## Shading Entire Packages
48 | If you wish to shade all of the assemblies in a particular package and its transitive dependencies, you can use the `Shade` property:
49 | ```xml
50 |
51 |
52 |
53 | ```
54 | 
55 | 
56 |
57 | ## Shading Assemblies Eclipsed by Explicit Package References
58 | When you have specified a newer version of a transitive dependency in your project, NuGet will eclipse this transitive version and as a performance optimization not download it. This means that the assemblies won't be available in the global packages folder to shade. To workaround this issue, the assembly shader will log an error indicating that you need to tell NuGet to download the dependency with a `` item.
59 |
60 | In the below example since `PackageZ` version `2.0.0` is declared explicitly, the transitive dependency of `PackageA` on `PackageZ` version `1.0.0` will be eclipsed and not made available for shading.
61 |
62 | ```xml
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 | ```
71 |
72 | You will need to specify a `` item to indicate to NuGet to still make it available:
73 | ```xml
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 | ```
84 |
85 |
86 | ## Limitations
87 | Assembly shading can be a great way to fix runtime issues with dependencies, but it does have some limitations.
88 |
89 | - Shaded assemblies are strong name signed with a new public key pair. In the process, Authenticode signatures are lost.
90 | - Since a shaded assembly is loaded side-by-side with a newer version, you will not be able to pass types around between the two versions. You will get a compile-time error if you attempt to do this. If you have to pass
91 | types around between assemblies, shading will not be possible.
92 | - Assembly references will be updated because they are easy to discover but any code that uses reflection to load types will not be updated. This includes `Assembly.Load` and `Assembly.LoadFrom`.
93 | If you have code that uses reflection to load types from a shaded assembly, you will need to update it to use the new assembly name.
94 |
--------------------------------------------------------------------------------
/build/PackageIcon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffkl/AssemblyShader/f289db121a8541219b93c0afd051b65017427846/build/PackageIcon.png
--------------------------------------------------------------------------------
/build/UnitTest.runsettings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 0
5 | true
6 |
7 |
8 |
9 |
10 |
11 |
12 | quiet
13 |
14 |
15 |
16 |
17 |
18 |
19 | denied
20 | 90
21 | 0
22 | true
23 | true
24 | quiet
25 | false
26 |
27 |
28 |
--------------------------------------------------------------------------------
/build/key.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffkl/AssemblyShader/f289db121a8541219b93c0afd051b65017427846/build/key.snk
--------------------------------------------------------------------------------
/src/AssemblyShader.UnitTests/AssemblyShader.UnitTests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net472;net8.0;net9.0
4 | false
5 | $(NoWarn);SA0001;SA1600
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/src/AssemblyShader.UnitTests/GetAssembliesToShadeTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using AssemblyShader.Tasks;
6 | using Microsoft.Build.Framework;
7 | using Microsoft.Build.Utilities;
8 | using Shouldly;
9 | using System.Collections.Generic;
10 | using System.IO;
11 | using System.Reflection;
12 | using Xunit;
13 |
14 | namespace AssemblyShader.UnitTests
15 | {
16 | public sealed class GetAssembliesToShadeTests : TestBase
17 | {
18 | [Fact(Skip = "Skipping for now")]
19 | public void Test1()
20 | {
21 | PackageIdentity packageMicrosoftNETTestSdk = new PackageIdentity("Microsoft.NET.Test.Sdk", "17.3.0");
22 | PackageIdentity packageMicrosoftNETCommunication = new PackageIdentity("Microsoft.NET.Communication", "17.3.0");
23 | PackageIdentity packageMicrosoftNETLogging = new PackageIdentity("Microsoft.NET.Logging", "17.3.0");
24 | PackageIdentity packageNewtonsoftJson9 = new PackageIdentity("Newtonsoft.Json", "9.0.1");
25 | PackageIdentity packageNewtonsoftJson12 = new PackageIdentity("Newtonsoft.Json", "12.0.3");
26 | PackageIdentity packageMicrosoftJsonBson = new PackageIdentity("Microsoft.Json.Bson", "1.0.2");
27 |
28 | string pathNewtonsoftJson12 = Path.Combine(TestDirectory, "Newtonsoft.Json", "12.0.3", "lib", "net45", "Newtonsoft.Json.dll");
29 | string pathNewtonsoftJson9 = Path.Combine(TestDirectory, "Newtonsoft.Json", "9.0.1", "lib", "net45", "Newtonsoft.Json.dll");
30 | string pathNewtonsoftJsonBson = Path.Combine(TestDirectory, "Newtonsoft.Json.Bson", "1.0.2", "lib", "net45", "Newtonsoft.Json.Bson.dll");
31 | string pathMicrosoftNETTestSdk = Path.Combine(TestDirectory, packageMicrosoftNETTestSdk.Id, packageMicrosoftNETTestSdk.Version, "lib", "net45", $"{packageMicrosoftNETTestSdk.Id}.dll");
32 | string pathMicrosoftNETCommunication = Path.Combine(TestDirectory, packageMicrosoftNETCommunication.Id, packageMicrosoftNETCommunication.Version, "lib", "net45", $"{packageMicrosoftNETCommunication.Id}.dll");
33 | string pathMicrosoftNETLogging = Path.Combine(TestDirectory, packageMicrosoftNETLogging.Id, packageMicrosoftNETLogging.Version, "lib", "net45", $"{packageMicrosoftNETLogging.Id}.dll");
34 |
35 | AssemblyName assemblyNameNewtonsoftJson9 = new AssemblyName("Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed");
36 | AssemblyName assemblyNameNewtonsoftJson12 = new AssemblyName("Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed");
37 | AssemblyName assemblyNameNewtonsoftJsonBson = new AssemblyName("Newtonsoft.Json.Bson, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed");
38 | AssemblyName assemblyNameMicrosoftNETTestSdk = new AssemblyName("Microsoft.NET.Test.Sdk, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed");
39 | AssemblyName assemblyNameMicrosoftNETCommunication = new AssemblyName("Microsoft.NET.Communication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed");
40 | AssemblyName assemblyNameMicrosoftNETLogging = new AssemblyName("Microsoft.NET.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed");
41 |
42 | INuGetProjectAssetsFileLoader assetsFileLoader = new MockNuGetProjectAssetsFileLoader
43 | {
44 | [".NETFramework,Version=v4.7.2"] = new Dictionary>
45 | {
46 | [packageMicrosoftNETTestSdk] = new HashSet
47 | {
48 | packageNewtonsoftJson9,
49 | },
50 | [packageMicrosoftJsonBson] = new HashSet
51 | {
52 | packageNewtonsoftJson12,
53 | },
54 | },
55 | };
56 |
57 | ITaskItem[] packageReferences = new ITaskItem[]
58 | {
59 | new TaskItem("Microsoft.NET.Test.Sdk", new Dictionary
60 | {
61 | { "Version", "17.3.0" },
62 | { "ShadeDependencies", "Newtonsoft.Json" },
63 | }),
64 | new TaskItem("Microsoft.Json.Bson", new Dictionary
65 | {
66 | { "Version", "1.0.2" },
67 | }),
68 | };
69 |
70 | ITaskItem[] references = new ITaskItem[]
71 | {
72 | new TaskItem(pathMicrosoftNETTestSdk, new Dictionary
73 | {
74 | { "FullPath", pathMicrosoftNETTestSdk },
75 | }),
76 | new TaskItem(pathNewtonsoftJson12, new Dictionary
77 | {
78 | { "FullPath", pathNewtonsoftJson12 },
79 | }),
80 | new TaskItem(pathNewtonsoftJsonBson, new Dictionary
81 | {
82 | { "FullPath", pathNewtonsoftJsonBson },
83 | }),
84 | new TaskItem(pathMicrosoftNETCommunication, new Dictionary
85 | {
86 | { "FullPath", pathMicrosoftNETCommunication },
87 | }),
88 | new TaskItem(pathMicrosoftNETLogging, new Dictionary
89 | {
90 | { "FullPath", pathMicrosoftNETLogging },
91 | }),
92 | };
93 |
94 | ITaskItem[] packageDownloads = new ITaskItem[]
95 | {
96 | new TaskItem(packageNewtonsoftJson9.Id, new Dictionary
97 | {
98 | { "Version", $"[{packageNewtonsoftJson9.Version}]" },
99 | }),
100 | };
101 |
102 | MockPackageAssemblyResolver packageAssemblyResolver = new MockPackageAssemblyResolver
103 | {
104 | [packageNewtonsoftJson9] = new List
105 | {
106 | new PackageAssembly(pathNewtonsoftJson9, string.Empty, assemblyNameNewtonsoftJson9),
107 | },
108 | [packageNewtonsoftJson12] = new List
109 | {
110 | new PackageAssembly(pathNewtonsoftJson12, string.Empty, assemblyNameNewtonsoftJson12),
111 | },
112 | };
113 |
114 | MockAssemblyInformationReader assemblyReferenceReader = new MockAssemblyInformationReader
115 | {
116 | [assemblyNameNewtonsoftJson9.FullName] = new List
117 | {
118 | new AssemblyReference(pathMicrosoftNETLogging, assemblyNameMicrosoftNETLogging),
119 | },
120 | [assemblyNameMicrosoftNETLogging.FullName] = new List
121 | {
122 | new AssemblyReference(pathMicrosoftNETCommunication, assemblyNameMicrosoftNETCommunication),
123 | },
124 | [assemblyNameMicrosoftNETCommunication.FullName] = new List()
125 | {
126 | new AssemblyReference(pathMicrosoftNETTestSdk, assemblyNameMicrosoftNETTestSdk),
127 | },
128 | [assemblyNameNewtonsoftJson12.FullName] = new List
129 | {
130 | new AssemblyReference(pathNewtonsoftJsonBson, assemblyNameNewtonsoftJsonBson),
131 | },
132 | [assemblyNameNewtonsoftJsonBson.FullName] = new List(),
133 | [assemblyNameMicrosoftNETTestSdk.FullName] = new List(),
134 | };
135 |
136 | IInternalsVisibleToReader internalsVisibleToReader = new MockInternalsVisibleToReader
137 | {
138 | [pathNewtonsoftJson9] = "Newtonsoft.Json, PublicKey=Some_Public_Key",
139 | };
140 |
141 | GetAssembliesToShade task = new GetAssembliesToShade(assetsFileLoader, packageAssemblyResolver, assemblyReferenceReader, internalsVisibleToReader)
142 | {
143 | IntermediateOutputPath = Path.Combine(TestDirectory, "obj"),
144 | PackageDownloads = packageDownloads,
145 | PackageReferences = packageReferences,
146 | ProjectAssetsFile = Path.Combine(TestDirectory, "obj", "project.assets.json"),
147 | References = references,
148 | ShadedAssemblyKeyFile = Path.Combine(TestAssemblyDirectory, "shaded.snk"),
149 | TargetFramework = "net472",
150 | TargetFrameworkMoniker = ".NETFramework,Version=v4.7.2",
151 | };
152 |
153 | bool result = task.Execute();
154 |
155 | result.ShouldBeTrue();
156 |
157 | ITaskItem[] assembliesToShade = task.AssembliesToShade;
158 |
159 | // TODO: Validate items
160 | }
161 | }
162 | }
--------------------------------------------------------------------------------
/src/AssemblyShader.UnitTests/MockAssemblyInformationReader.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System;
6 | using System.Collections.Generic;
7 |
8 | namespace AssemblyShader.UnitTests
9 | {
10 | internal sealed class MockAssemblyInformationReader : Dictionary>, IAssemblyInformationReader
11 | {
12 | public MockAssemblyInformationReader()
13 | : base(StringComparer.OrdinalIgnoreCase)
14 | {
15 | }
16 |
17 | public AssemblyInformation GetAssemblyInformation(IEnumerable assemblyPaths)
18 | {
19 | AssemblyInformation assemblyInformation = new AssemblyInformation();
20 |
21 | foreach (KeyValuePair> i in this)
22 | {
23 | assemblyInformation.AssemblyReferences.Add(i.Key, i.Value);
24 | }
25 |
26 | return assemblyInformation;
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/src/AssemblyShader.UnitTests/MockInternalsVisibleToReader.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System;
6 | using System.Collections.Generic;
7 |
8 | namespace AssemblyShader.UnitTests
9 | {
10 | internal sealed class MockInternalsVisibleToReader : Dictionary, IInternalsVisibleToReader
11 | {
12 | public MockInternalsVisibleToReader()
13 | : base(StringComparer.OrdinalIgnoreCase)
14 | {
15 | }
16 |
17 | public string Read(string path)
18 | {
19 | if (TryGetValue(path, out string? result))
20 | {
21 | return result;
22 | }
23 |
24 | throw new Exception($"The current mock InternalsVisibleToReader did not specify a value for the assembly '{path}");
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/src/AssemblyShader.UnitTests/MockNuGetProjectAssetsFileLoader.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System.Collections.Generic;
6 |
7 | namespace AssemblyShader.UnitTests
8 | {
9 | internal sealed class MockNuGetProjectAssetsFileLoader : Dictionary>>, INuGetProjectAssetsFileLoader
10 | {
11 | public NuGetProjectAssetsFile Load(string projectDirectory, string projectAssetsFile)
12 | {
13 | NuGetProjectAssetsFile assetsFile = new NuGetProjectAssetsFile();
14 |
15 | foreach (KeyValuePair>> item in this)
16 | {
17 | assetsFile[item.Key] = new NuGetProjectAssetsFileSection();
18 |
19 | foreach (KeyValuePair> package in item.Value)
20 | {
21 | assetsFile[item.Key].Packages[package.Key] = package.Value;
22 | }
23 | }
24 |
25 | return assetsFile;
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/src/AssemblyShader.UnitTests/MockPackageAssemblyResolver.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System.Collections.Generic;
6 |
7 | namespace AssemblyShader.UnitTests
8 | {
9 | internal sealed class MockPackageAssemblyResolver : Dictionary>, IPackageAssemblyResolver
10 | {
11 | public IEnumerable GetNearest(PackageIdentity packageIdentity, string nuGetPackageRoot, string targetFramework, string[] fallbackTargetFrameworks)
12 | {
13 | return this[packageIdentity];
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/src/AssemblyShader.UnitTests/StringStream.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System;
6 | using System.IO;
7 | using System.Text;
8 |
9 | namespace AssemblyShader.UnitTests
10 | {
11 | internal sealed class StringStream : Stream, IDisposable
12 | {
13 | private readonly MemoryStream _stream;
14 |
15 | public StringStream(string value)
16 | {
17 | _stream = new MemoryStream(Encoding.UTF8.GetBytes(value));
18 | }
19 |
20 | public override bool CanRead => _stream.CanRead;
21 |
22 | public override bool CanSeek => _stream.CanSeek;
23 |
24 | public override bool CanWrite => _stream.CanWrite;
25 |
26 | public override long Length => _stream.Length;
27 |
28 | public override long Position { get => _stream.Position; set => _stream.Position = value; }
29 |
30 | public override void Flush() => _stream.Flush();
31 |
32 | public override int Read(byte[] buffer, int offset, int count) => _stream.Read(buffer, offset, count);
33 |
34 | public override long Seek(long offset, SeekOrigin origin) => _stream.Seek(offset, origin);
35 |
36 | public override void SetLength(long value) => _stream.SetLength(value);
37 |
38 | public override void Write(byte[] buffer, int offset, int count) => _stream.Write(buffer, offset, count);
39 |
40 | protected override void Dispose(bool disposing)
41 | {
42 | if (disposing)
43 | {
44 | _stream.Dispose();
45 | }
46 |
47 | base.Dispose(disposing);
48 | }
49 | }
50 | }
--------------------------------------------------------------------------------
/src/AssemblyShader.UnitTests/TestBase.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using Microsoft.Build.Utilities.ProjectCreation;
6 | using System;
7 | using System.IO;
8 |
9 | namespace AssemblyShader.UnitTests
10 | {
11 | public abstract class TestBase : MSBuildTestBase, IDisposable
12 | {
13 | private static readonly DirectoryInfo _testAssemblyDirectory = new DirectoryInfo(Path.GetDirectoryName(typeof(TestBase).Assembly.Location)!);
14 |
15 | private readonly DirectoryInfo _testDirectory;
16 |
17 | public TestBase()
18 | {
19 | _testDirectory = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")));
20 | }
21 |
22 | public string TestAssemblyDirectory => _testAssemblyDirectory!.FullName;
23 |
24 | public string TestDirectory => _testDirectory.FullName;
25 |
26 | public void Dispose()
27 | {
28 | _testDirectory.Delete(recursive: true);
29 | }
30 | }
31 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/AssemblyInformation.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | namespace AssemblyShader
6 | {
7 | internal sealed class AssemblyInformation
8 | {
9 | public AssemblyReferencesByAssemblyName AssemblyReferences { get; } = new();
10 |
11 | public FriendAssembliesByInternalsVisibleTo FriendAssemblies { get; } = new();
12 | }
13 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/AssemblyInformationReader.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using Mono.Cecil;
6 | using System;
7 | using System.Collections.Generic;
8 | using System.IO;
9 | using System.Linq;
10 |
11 | namespace AssemblyShader
12 | {
13 | internal sealed class AssemblyInformationReader : IAssemblyInformationReader
14 | {
15 | public AssemblyInformation GetAssemblyInformation(IEnumerable assemblyPaths)
16 | {
17 | AssemblyInformation assemblyInformation = new AssemblyInformation();
18 |
19 | using DefaultAssemblyResolver resolver = new DefaultAssemblyResolver();
20 |
21 | foreach (string assemblyPath in assemblyPaths)
22 | {
23 | FileInfo assemblyFileInfo = new FileInfo(assemblyPath);
24 |
25 | if (!assemblyFileInfo.Exists)
26 | {
27 | continue;
28 | }
29 |
30 | resolver.AddSearchDirectory(assemblyFileInfo.DirectoryName);
31 |
32 | using AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(assemblyFileInfo.FullName, new ReaderParameters
33 | {
34 | AssemblyResolver = resolver,
35 | ReadSymbols = File.Exists(Path.ChangeExtension(assemblyFileInfo.FullName, ".pdb")),
36 | });
37 |
38 | if (!assemblyInformation.AssemblyReferences.ContainsKey(assembly.FullName))
39 | {
40 | assemblyInformation.AssemblyReferences.Add(assembly.FullName, new List());
41 | }
42 |
43 | foreach (AssemblyNameReference assemblyReference in assembly.MainModule.AssemblyReferences)
44 | {
45 | if (!assemblyInformation.AssemblyReferences.TryGetValue(assemblyReference.FullName, out List? assemblyReferences))
46 | {
47 | assemblyReferences = new List();
48 |
49 | assemblyInformation.AssemblyReferences.Add(assemblyReference.FullName, assemblyReferences);
50 | }
51 |
52 | assemblyReferences.Add(new AssemblyReference(assemblyFileInfo, assembly.Name.FullName));
53 | }
54 |
55 | foreach (CustomAttribute internalsVisibleToAttribute in assembly.CustomAttributes.Where(i => string.Equals(i.AttributeType.FullName, "System.Runtime.CompilerServices.InternalsVisibleToAttribute", StringComparison.Ordinal)))
56 | {
57 | if (internalsVisibleToAttribute.ConstructorArguments[0].Value is string value)
58 | {
59 | if (!assemblyInformation.FriendAssemblies.TryGetValue(value, out List? assemblyReferences))
60 | {
61 | assemblyReferences = new List();
62 |
63 | assemblyInformation.FriendAssemblies.Add(value, assemblyReferences);
64 | }
65 |
66 | assemblyReferences.Add(new AssemblyReference(assemblyFileInfo, assembly.Name.FullName));
67 | }
68 | }
69 | }
70 |
71 | return assemblyInformation;
72 | }
73 | }
74 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/AssemblyNameCache.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System;
6 | using System.Collections.Concurrent;
7 | using System.Reflection;
8 |
9 | namespace AssemblyShader
10 | {
11 | ///
12 | /// Represents a cache of assembly names by file path. If the assembly name has already been read for a particular assembly path, the cached value is returned. If an assembly file changes on disk, the assembly name is not reloaded.
13 | ///
14 | internal static class AssemblyNameCache
15 | {
16 | private static readonly ConcurrentDictionary> Cache = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase);
17 |
18 | public static AssemblyName GetAssemblyName(string path) => Cache.GetOrAdd(path, new Lazy(() => AssemblyName.GetAssemblyName(path))).Value;
19 | }
20 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/AssemblyReference.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System.IO;
6 | using System.Reflection;
7 |
8 | namespace AssemblyShader
9 | {
10 | internal readonly record struct AssemblyReference
11 | {
12 | public AssemblyReference(string fullPath, AssemblyName name)
13 | {
14 | FullPath = fullPath;
15 | Name = name;
16 | }
17 |
18 | public AssemblyReference(string fullPath)
19 | : this(fullPath, AssemblyNameCache.GetAssemblyName(fullPath))
20 | {
21 | }
22 |
23 | public AssemblyReference(FileInfo fullPath, string assemblyName)
24 | : this(fullPath.FullName, new AssemblyName(assemblyName))
25 | {
26 | }
27 |
28 | public readonly string FullPath { get; }
29 |
30 | public readonly AssemblyName Name { get; }
31 | }
32 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/AssemblyReferencesByAssemblyName.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System;
6 | using System.Collections.Generic;
7 |
8 | namespace AssemblyShader
9 | {
10 | internal sealed class AssemblyReferencesByAssemblyName : Dictionary>
11 | {
12 | public AssemblyReferencesByAssemblyName()
13 | : base(StringComparer.OrdinalIgnoreCase)
14 | {
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/AssemblyShader.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | netstandard2.0;net472
4 | ..\..\artifacts\$(MSBuildProjectName)
5 | build\
6 | true
7 | An MSBuild extension that allows you to shade assembly dependencies.
8 | true
9 | true
10 | true
11 | true
12 | true
13 | $(NoWarn);NU5128
14 | true
15 | snupkg
16 |
17 |
18 |
19 | All
20 |
21 |
22 |
23 |
25 |
27 |
28 |
29 |
30 |
32 |
33 |
35 |
36 |
37 |
38 | True
39 | True
40 | Strings.resx
41 |
42 |
43 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
57 |
58 |
61 |
62 |
64 |
65 |
67 |
68 |
69 |
70 |
--------------------------------------------------------------------------------
/src/AssemblyShader/AssemblyToRename.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using Microsoft.Build.Framework;
6 | using Mono.Cecil;
7 | using System;
8 | using System.Collections;
9 | using System.Collections.Generic;
10 | using System.Diagnostics;
11 | using System.Reflection;
12 | using System.Runtime.CompilerServices;
13 |
14 | namespace AssemblyShader
15 | {
16 | ///
17 | /// Represents an assembly that will be renamed.
18 | ///
19 | [DebuggerDisplay("{AssemblyName, nq} => {ShadedAssemblyName,nq} ({ShadedPath,nq}}")]
20 | internal sealed class AssemblyToRename : IEquatable
21 | {
22 | ///
23 | /// Initializes a new instance of the class.
24 | ///
25 | /// The full path to the assembly.
26 | /// The of the assembly.
27 | /// An optional to populate the dictionary with.
28 | public AssemblyToRename(string fullPath, AssemblyName assemblyName, ITaskItem? taskItem = null)
29 | {
30 | FullPath = fullPath;
31 | AssemblyName = assemblyName;
32 | Metadata = taskItem == null ? new Dictionary(StringComparer.OrdinalIgnoreCase) : taskItem.CloneCustomMetadata();
33 | }
34 |
35 | ///
36 | /// Gets the of the assembly.
37 | ///
38 | public AssemblyName AssemblyName { get; }
39 |
40 | ///
41 | /// Gets or sets the destination subdirectory for the assembly.
42 | ///
43 | public string? DestinationSubdirectory { get; set; }
44 |
45 | ///
46 | /// Gets the full path to the assembly.
47 | ///
48 | public string FullPath { get; }
49 |
50 | ///
51 | /// Gets or sets the value of a that would reference the assembly.
52 | ///
53 | public string? InternalsVisibleTo { get; set; }
54 |
55 | ///
56 | /// Gets an containing the metadata for an MSBuild item.
57 | ///
58 | public IDictionary Metadata { get; }
59 |
60 | ///
61 | /// Gets or sets the of the shaded assembly.
62 | ///
63 | public AssemblyNameDefinition? ShadedAssemblyName { get; set; }
64 |
65 | ///
66 | /// Gets or sets the value of a that would reference the assembly after it has been shaded.
67 | ///
68 | public string? ShadedInternalsVisibleTo { get; set; }
69 |
70 | ///
71 | /// Gets or sets the full path to the shaded assembly.
72 | ///
73 | public string? ShadedPath { get; set; }
74 |
75 | public bool Equals(AssemblyToRename? other)
76 | {
77 | return other is not null && string.Equals(AssemblyName.FullName, other.AssemblyName.FullName);
78 | }
79 | }
80 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/DotNetAssemblyResolver.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System;
6 | using System.IO;
7 | using System.Linq;
8 |
9 | namespace AssemblyShader
10 | {
11 | internal static class DotNetAssemblyResolver
12 | {
13 | private static readonly char[] Comma = new[] { ',' };
14 |
15 | private static readonly string? DotNetBasePath = TryFindOnPath(Environment.OSVersion.Platform == PlatformID.Unix ? "dotnet" : "dotnet.exe", out FileInfo? dotnetFileInfo)
16 | ? dotnetFileInfo!.DirectoryName
17 | : null;
18 |
19 | private static readonly char[] EqualSign = new[] { '=' };
20 |
21 | private static readonly Version ZeroVersion = new Version(0, 0, 0, 0);
22 |
23 | private enum TargetFrameworkIdentifier
24 | {
25 | None,
26 | NETFramework,
27 | NETCoreApp,
28 | NETStandard,
29 | Silverlight,
30 | NET,
31 | }
32 |
33 | internal static bool TryGetReferenceAssemblyPath(string targetFramework, out string? directory)
34 | {
35 | directory = null;
36 |
37 | if (DotNetBasePath is null)
38 | {
39 | return false;
40 | }
41 |
42 | (TargetFrameworkIdentifier targetFrameworkMoniker, Version version) = ParseTargetFramework(targetFramework);
43 |
44 | string identifier, identifierExt;
45 |
46 | switch (targetFrameworkMoniker)
47 | {
48 | case TargetFrameworkIdentifier.NETCoreApp:
49 | identifier = "Microsoft.NETCore.App";
50 | identifierExt = $"netcoreapp{version.Major}.{version.Minor}";
51 | break;
52 |
53 | case TargetFrameworkIdentifier.NETStandard:
54 | identifier = "NETStandard.Library";
55 | identifierExt = $"netstandard{version.Major}.{version.Minor}";
56 | break;
57 |
58 | case TargetFrameworkIdentifier.NET:
59 | identifier = "Microsoft.NETCore.App";
60 | identifierExt = $"net{version.Major}.{version.Minor}";
61 | break;
62 |
63 | default:
64 | return false;
65 | }
66 |
67 | string basePath = Path.Combine(DotNetBasePath, "packs", $"{identifier}.Ref");
68 |
69 | string? versionFolder = GetClosestVersionFolder(basePath, version);
70 |
71 | if (versionFolder is null)
72 | {
73 | return false;
74 | }
75 |
76 | directory = Path.Combine(basePath, versionFolder, "ref", identifierExt);
77 |
78 | return true;
79 | }
80 |
81 | private static string? GetClosestVersionFolder(string basePath, Version version)
82 | {
83 | (Version? Version, string? DirectoryName) match = new DirectoryInfo(basePath).EnumerateDirectories()
84 | .Select(i => ParseVersion(i.Name))
85 | .Where(i => i.Version != null)
86 | .OrderBy(i => i)
87 | .FirstOrDefault(i => i.Version >= version);
88 |
89 | return match != default ? match!.DirectoryName : version.ToString();
90 | }
91 |
92 | private static (TargetFrameworkIdentifier TargetFrameworkIdentifier, Version Version) ParseTargetFramework(string targetFramework)
93 | {
94 | if (string.IsNullOrEmpty(targetFramework))
95 | {
96 | return (TargetFrameworkIdentifier.NETFramework, ZeroVersion);
97 | }
98 |
99 | string[] tokens = targetFramework.Split(Comma, 2);
100 |
101 | if (tokens.Length != 2)
102 | {
103 | return (TargetFrameworkIdentifier.None, ZeroVersion);
104 | }
105 |
106 | TargetFrameworkIdentifier identifier;
107 |
108 | switch (tokens[0].Trim().ToUpperInvariant())
109 | {
110 | case ".NETCOREAPP":
111 | identifier = TargetFrameworkIdentifier.NETCoreApp;
112 | break;
113 |
114 | case ".NETSTANDARD":
115 | identifier = TargetFrameworkIdentifier.NETStandard;
116 | break;
117 |
118 | case "SILVERLIGHT":
119 | identifier = TargetFrameworkIdentifier.Silverlight;
120 | break;
121 |
122 | default:
123 | identifier = TargetFrameworkIdentifier.NETFramework;
124 | break;
125 | }
126 |
127 | Version? version = null;
128 |
129 | for (int i = 1; i < tokens.Length; i++)
130 | {
131 | string[] pair = tokens[i].Trim().Split(EqualSign, 2);
132 |
133 | if (pair.Length != 2)
134 | {
135 | continue;
136 | }
137 |
138 | switch (pair[0].Trim().ToUpperInvariant())
139 | {
140 | case "VERSION":
141 | string versionString = pair[1].Trim().TrimStart('v');
142 |
143 | if ((identifier == TargetFrameworkIdentifier.NETCoreApp || identifier == TargetFrameworkIdentifier.NETStandard) && versionString.Length == 3)
144 | {
145 | versionString += ".0";
146 | }
147 |
148 | if (!Version.TryParse(versionString, out version))
149 | {
150 | version = null;
151 | }
152 |
153 | if (version?.Major >= 5 && identifier == TargetFrameworkIdentifier.NETCoreApp)
154 | {
155 | identifier = TargetFrameworkIdentifier.NET;
156 | }
157 |
158 | break;
159 | }
160 | }
161 |
162 | return (identifier, version ?? ZeroVersion);
163 | }
164 |
165 | private static (Version? Version, string? DirectoryName) ParseVersion(string name)
166 | {
167 | try
168 | {
169 | return (new Version(RemoveTrailingVersionInfo()), name);
170 | }
171 | catch (Exception)
172 | {
173 | return (null, null);
174 | }
175 |
176 | string RemoveTrailingVersionInfo()
177 | {
178 | string shortName = name;
179 | int dashIndex = shortName.IndexOf('-');
180 |
181 | if (dashIndex > 0)
182 | {
183 | shortName = shortName.Remove(dashIndex);
184 | }
185 |
186 | return shortName;
187 | }
188 | }
189 |
190 | private static bool TryFindOnPath(string exe, out FileInfo? fileInfo)
191 | {
192 | fileInfo = (Environment.GetEnvironmentVariable("PATH") ?? string.Empty)
193 | .Split(Path.PathSeparator)
194 | .Where(i => !string.IsNullOrWhiteSpace(i))
195 | .Select(i => new DirectoryInfo(i.Trim()))
196 | .Where(i => i.Exists)
197 | .Select(i => new FileInfo(Path.Combine(i.FullName, $"{exe}")))
198 | .FirstOrDefault(i => i.Exists);
199 |
200 | return fileInfo != null;
201 | }
202 | }
203 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/ExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System;
6 |
7 | namespace AssemblyShader
8 | {
9 | internal static class ExtensionMethods
10 | {
11 | public static string ThrowIfNull(this string value, string paramName)
12 | {
13 | if (string.IsNullOrWhiteSpace(value))
14 | {
15 | throw new ArgumentNullException(paramName);
16 | }
17 |
18 | return value;
19 | }
20 |
21 | public static T ThrowIfNull(this T obj, string paramName)
22 | where T : class
23 | {
24 | if (obj is null)
25 | {
26 | throw new ArgumentNullException(paramName);
27 | }
28 |
29 | return obj;
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/FileSystemInfoFullNameEqualityComparer.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System;
6 | using System.Collections.Generic;
7 | using System.IO;
8 | using System.Runtime.InteropServices;
9 |
10 | namespace AssemblyShader
11 | {
12 | ///
13 | /// Represents an implementation of that compares objects by the value of their property.
14 | ///
15 | internal sealed class FileSystemInfoFullNameEqualityComparer : IEqualityComparer
16 | {
17 | private FileSystemInfoFullNameEqualityComparer()
18 | {
19 | }
20 |
21 | ///
22 | /// Gets a static singleton for the class.
23 | ///
24 | public static FileSystemInfoFullNameEqualityComparer Instance { get; } = new FileSystemInfoFullNameEqualityComparer();
25 |
26 | ///
27 | /// Determines whether the specified objects are equal by comparing their property.
28 | ///
29 | /// The first to compare.
30 | /// The second to compare.
31 | /// if the specified objects' property are equal, otherwise .
32 | public bool Equals(FileSystemInfo? x, FileSystemInfo? y)
33 | {
34 | return x is not null
35 | && y is not null
36 | && string.Equals(x.FullName, y.FullName, RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
37 | }
38 |
39 | ///
40 | /// Returns a hash code for the specified object's property.
41 | ///
42 | /// The for which a hash code is to be returned.
43 | /// A hash code for the specified object's property..
44 | public int GetHashCode(FileSystemInfo obj)
45 | {
46 | #if NETFRAMEWORK || NETSTANDARD
47 | return obj.FullName.GetHashCode();
48 | #else
49 | return obj.FullName.GetHashCode(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
50 | #endif
51 | }
52 | }
53 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/FriendAssembliesByInternalsVisibleTo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System;
6 | using System.Collections.Generic;
7 |
8 | namespace AssemblyShader
9 | {
10 | internal sealed class FriendAssembliesByInternalsVisibleTo : Dictionary>
11 | {
12 | public FriendAssembliesByInternalsVisibleTo()
13 | : base(StringComparer.OrdinalIgnoreCase)
14 | {
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/IAssemblyInformationReader.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System.Collections.Generic;
6 |
7 | namespace AssemblyShader
8 | {
9 | ///
10 | /// Represents an interface for a class that reads assembly references.
11 | ///
12 | internal interface IAssemblyInformationReader
13 | {
14 | ///
15 | /// Gets assembly information for the specified assembly paths.
16 | ///
17 | /// An containing paths to assemblies.
18 | /// An object containing information about the assemblies.
19 | AssemblyInformation GetAssemblyInformation(IEnumerable assemblyPaths);
20 | }
21 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/IInternalsVisibleToReader.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System.Runtime.CompilerServices;
6 |
7 | namespace AssemblyShader
8 | {
9 | ///
10 | /// Represents an interface for a class that gets the value for an for assemblies.
11 | ///
12 | internal interface IInternalsVisibleToReader
13 | {
14 | ///
15 | /// Gets the value for an for the specified assembly path.
16 | ///
17 | /// The full path to the assembly to get a value for an .
18 | /// A value for an for the specified assembly.
19 | public string Read(string path);
20 | }
21 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/INuGetProjectAssetsFileLoader.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System.Collections.Generic;
6 |
7 | namespace AssemblyShader
8 | {
9 | ///
10 | /// Represents an interface for a class that loads NuGet project assets files.
11 | ///
12 | internal interface INuGetProjectAssetsFileLoader
13 | {
14 | ///
15 | /// Loads the specified NuGet assets file.
16 | ///
17 | /// The full path to the project's directory.
18 | /// The full path to the NuGet assets file to load.
19 | /// An containing target frameworks and a list of packages with their dependencies.
20 | NuGetProjectAssetsFile? Load(string projectDirectory, string projectAssetsFile);
21 | }
22 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/IPackageAssemblyResolver.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System.Collections.Generic;
6 |
7 | namespace AssemblyShader
8 | {
9 | ///
10 | /// Represents an interface for a class that resolves assemblies in a NuGet package.
11 | ///
12 | internal interface IPackageAssemblyResolver
13 | {
14 | ///
15 | /// Gets the assembly paths for the specified package based on the supported target frameworks.
16 | ///
17 | /// The of the package.
18 | /// The root directory containing NuGet packages.
19 | /// The target framework of the current project.
20 | /// An array of fallback target frameworks of the current project.
21 | /// An containing the resolved assemblies from the package for the target framework.
22 | IEnumerable? GetNearest(PackageIdentity packageIdentity, string nuGetPackageRoot, string targetFramework, string[] fallbackTargetFrameworks);
23 | }
24 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/InternalsVisibleToReader.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using Mono.Cecil;
6 | using System;
7 | using System.Collections.Concurrent;
8 | using System.Linq;
9 |
10 | namespace AssemblyShader
11 | {
12 | internal sealed class InternalsVisibleToReader : IInternalsVisibleToReader
13 | {
14 | private static readonly ConcurrentDictionary> Cache = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase);
15 |
16 | public string Read(string path)
17 | {
18 | Lazy result = Cache.GetOrAdd(path, new Lazy(() => GetInternalsVisibleToAttributeValue(path)));
19 |
20 | return result.Value;
21 | }
22 |
23 | private static string GetInternalsVisibleToAttributeValue(string path)
24 | {
25 | using AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly(path);
26 |
27 | if (assemblyDefinition.Name.HasPublicKey)
28 | {
29 | return $"{assemblyDefinition.Name.Name}, PublicKey={string.Join(string.Empty, assemblyDefinition.Name.PublicKey.Select(i => i.ToString("x2")))}";
30 | }
31 |
32 | return assemblyDefinition.Name.Name;
33 | }
34 | }
35 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/ItemMetadataNames.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | namespace AssemblyShader
6 | {
7 | ///
8 | /// Represents the names of MSBuild item metadata.
9 | ///
10 | internal static class ItemMetadataNames
11 | {
12 | ///
13 | /// The assembly name.
14 | ///
15 | public const string AssemblyName = nameof(AssemblyName);
16 |
17 | ///
18 | /// The destination subdirectory.
19 | ///
20 | public const string DestinationSubdirectory = nameof(DestinationSubdirectory);
21 |
22 | ///
23 | /// The full path to the assembly.
24 | ///
25 | public const string FullPath = nameof(FullPath);
26 |
27 | ///
28 | /// The hint path of the assembly.
29 | ///
30 | public const string HintPath = nameof(HintPath);
31 |
32 | ///
33 | /// The previous value for the .
34 | ///
35 | public const string InternalsVisibleTo = nameof(InternalsVisibleTo);
36 |
37 | ///
38 | /// The project source file for a particular item in MSBuild.
39 | ///
40 | public const string MSBuildSourceProjectFile = nameof(MSBuildSourceProjectFile);
41 |
42 | ///
43 | /// The NuGet package version.
44 | ///
45 | public const string OriginalPath = nameof(OriginalPath);
46 |
47 | ///
48 | /// Whether or not to shade the package.
49 | ///
50 | public const string Shade = nameof(Shade);
51 |
52 | ///
53 | /// The shaded assembly name.
54 | ///
55 | public const string ShadedAssemblyName = nameof(ShadedAssemblyName);
56 |
57 | ///
58 | /// The list of dependencies to shade.
59 | ///
60 | public const string ShadeDependencies = nameof(ShadeDependencies);
61 |
62 | ///
63 | /// The shaded value for the .
64 | ///
65 | public const string ShadedInternalsVisibleTo = nameof(ShadedInternalsVisibleTo);
66 |
67 | ///
68 | /// The version of a NuGet package.
69 | ///
70 | public const string Version = nameof(Version);
71 |
72 | ///
73 | /// The version override of a NuGet package.
74 | ///
75 | public const string VersionOverride = nameof(VersionOverride);
76 | }
77 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/NuGetProjectAssetsFile.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System;
6 | using System.Collections.Generic;
7 |
8 | namespace AssemblyShader
9 | {
10 | internal sealed class NuGetProjectAssetsFile : Dictionary
11 | {
12 | public NuGetProjectAssetsFile()
13 | : base(StringComparer.OrdinalIgnoreCase)
14 | {
15 | }
16 |
17 | public Dictionary ProjectReferences { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase);
18 | }
19 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/NuGetProjectAssetsFileLoader.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using NuGet.Versioning;
6 | using System;
7 | using System.Collections.Concurrent;
8 | using System.Collections.Generic;
9 | using System.IO;
10 | using System.Runtime.InteropServices;
11 | using System.Text.Json;
12 |
13 | namespace AssemblyShader
14 | {
15 | internal sealed class NuGetProjectAssetsFileLoader : INuGetProjectAssetsFileLoader
16 | {
17 | private static readonly ConcurrentDictionary Lazy)> FileCache = new(FileSystemInfoFullNameEqualityComparer.Instance);
18 |
19 | public NuGetProjectAssetsFile? Load(string projectDirectory, string projectAssetsFile)
20 | {
21 | FileInfo fileInfo = new FileInfo(projectAssetsFile);
22 |
23 | if (!fileInfo.Exists)
24 | {
25 | return null;
26 | }
27 |
28 | (DateTime _, Lazy Lazy) cacheEntry = FileCache.AddOrUpdate(
29 | fileInfo,
30 | key => (key.LastWriteTime, new Lazy(() => ParseNuGetAssetsFile(projectDirectory, key.FullName))),
31 | (key, item) =>
32 | {
33 | DateTime lastWriteTime = key.LastWriteTime;
34 |
35 | if (item.LastWriteTime < lastWriteTime)
36 | {
37 | return (lastWriteTime, new Lazy(() => ParseNuGetAssetsFile(projectDirectory, key.FullName)));
38 | }
39 |
40 | return item;
41 | });
42 |
43 | return cacheEntry.Lazy.Value;
44 | }
45 |
46 | internal NuGetProjectAssetsFile ParseNuGetAssetsFile(string projectDirectory, string projectAssetsFile)
47 | {
48 | using FileStream stream = File.OpenRead(projectAssetsFile);
49 |
50 | return ParseNuGetAssetsFile(projectDirectory, stream);
51 | }
52 |
53 | internal NuGetProjectAssetsFile ParseNuGetAssetsFile(string projectDirectory, Stream stream)
54 | {
55 | NuGetProjectAssetsFile assetsFile = new();
56 |
57 | JsonDocumentOptions options = new JsonDocumentOptions
58 | {
59 | AllowTrailingCommas = true,
60 | };
61 |
62 | using (JsonDocument json = JsonDocument.Parse(stream, options))
63 | {
64 | foreach (JsonProperty targetFramework in json.RootElement.GetProperty("targets").EnumerateObject())
65 | {
66 | NuGetProjectAssetsFileSection nuGetProjectAssetsFileSection = new();
67 |
68 | Dictionary> packages = nuGetProjectAssetsFileSection.Packages;
69 |
70 | if (targetFramework.Value.ValueKind == JsonValueKind.Undefined)
71 | {
72 | continue;
73 | }
74 |
75 | foreach (JsonProperty item in targetFramework.Value.EnumerateObject())
76 | {
77 | string[] packageDetails = item.Name.Split('/');
78 |
79 | if (!NuGetVersion.TryParse(packageDetails[1], out NuGetVersion? nuGetVersion))
80 | {
81 | continue;
82 | }
83 |
84 | PackageIdentity packageIdentity = new PackageIdentity(packageDetails[0], nuGetVersion.ToNormalizedString());
85 |
86 | if (!packages.TryGetValue(packageIdentity, out HashSet? dependencies))
87 | {
88 | dependencies = new HashSet();
89 |
90 | packages[packageIdentity] = dependencies;
91 | }
92 |
93 | if (item.Value.TryGetProperty("dependencies", out JsonElement deps))
94 | {
95 | foreach (JsonProperty dependency in deps.EnumerateObject())
96 | {
97 | string? versionString = dependency.Value.GetString();
98 |
99 | if (versionString is null || !VersionRange.TryParse(versionString, out VersionRange? versionRange) || versionRange?.MinVersion == null)
100 | {
101 | continue;
102 | }
103 |
104 | dependencies.Add(new PackageIdentity(dependency.Name, versionRange.MinVersion.ToNormalizedString()));
105 | }
106 | }
107 | }
108 |
109 | bool added = false;
110 | int count = 0;
111 | do
112 | {
113 | count++;
114 | added = false;
115 |
116 | foreach (KeyValuePair> package in packages)
117 | {
118 | List dependenciesToAdd = new List();
119 |
120 | foreach (PackageIdentity dependency in package.Value)
121 | {
122 | if (packages.TryGetValue(dependency, out HashSet? dependencies))
123 | {
124 | dependenciesToAdd.AddRange(dependencies);
125 | }
126 | }
127 |
128 | foreach (PackageIdentity dependencyToAdd in dependenciesToAdd)
129 | {
130 | if (package.Value.Add(dependencyToAdd))
131 | {
132 | added = true;
133 | }
134 | }
135 | }
136 | }
137 | while (added);
138 |
139 | assetsFile[targetFramework.Name] = nuGetProjectAssetsFileSection;
140 | }
141 |
142 | foreach (JsonProperty library in json.RootElement.GetProperty("libraries").EnumerateObject())
143 | {
144 | if (!library.Value.TryGetProperty("type", out JsonElement type) || !string.Equals(type.GetString(), "project") || !library.Value.TryGetProperty("path", out JsonElement path))
145 | {
146 | continue;
147 | }
148 |
149 | string[] libraryDetails = library.Name.Split('/');
150 |
151 | PackageIdentity packageIdentity = new PackageIdentity(libraryDetails[0], libraryDetails[1]);
152 |
153 | string? relativePath = path.GetString();
154 |
155 | if (relativePath is null)
156 | {
157 | continue;
158 | }
159 |
160 | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
161 | {
162 | relativePath = relativePath.Replace('/', '\\');
163 | }
164 |
165 | FileInfo projectFileInfo = new FileInfo(Path.Combine(projectDirectory, relativePath));
166 |
167 | assetsFile.ProjectReferences[projectFileInfo.FullName] = packageIdentity;
168 | }
169 | }
170 |
171 | return assetsFile;
172 | }
173 | }
174 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/NuGetProjectAssetsFileSection.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System.Collections.Generic;
6 |
7 | namespace AssemblyShader
8 | {
9 | internal sealed class NuGetProjectAssetsFileSection
10 | {
11 | public Dictionary> Packages { get; } = new Dictionary>();
12 | }
13 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/PackageAssembly.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System.Reflection;
6 |
7 | namespace AssemblyShader
8 | {
9 | internal record struct PackageAssembly
10 | {
11 | public PackageAssembly(string path, string subDirectory, AssemblyName assemblyName)
12 | {
13 | Path = path;
14 | Subdirectory = subDirectory;
15 | Name = assemblyName;
16 | }
17 |
18 | public readonly string Path { get; }
19 |
20 | public readonly string Subdirectory { get; }
21 |
22 | public readonly AssemblyName Name { get; }
23 | }
24 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/PackageAssemblyResolver.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using NuGet.Frameworks;
6 | using System;
7 | using System.Collections.Generic;
8 | using System.IO;
9 | using System.Linq;
10 | using System.Reflection;
11 |
12 | namespace AssemblyShader
13 | {
14 | internal sealed class PackageAssemblyResolver : IPackageAssemblyResolver
15 | {
16 | public IEnumerable? GetNearest(PackageIdentity packageIdentity, string nuGetPackageRoot, string targetFramework, string[] fallbackTargetFrameworks)
17 | {
18 | string path = Path.Combine(nuGetPackageRoot, packageIdentity.Id.ToLower(), packageIdentity.Version.ToLower(), "lib");
19 |
20 | if (!Directory.Exists(path))
21 | {
22 | return null;
23 | }
24 |
25 | IEnumerable targetFrameworksToCheck = new List { targetFramework }.Concat(fallbackTargetFrameworks == null ? Array.Empty() : fallbackTargetFrameworks);
26 |
27 | List compatibleTargetFrameworks = Directory.EnumerateDirectories(path).Select(i => new DirectoryInfo(i)).ToList();
28 |
29 | DirectoryInfo? directory = null;
30 |
31 | foreach (string targetFrameworkToCheck in targetFrameworksToCheck)
32 | {
33 | directory = NuGetFrameworkUtility.GetNearest(
34 | compatibleTargetFrameworks,
35 | NuGetFramework.ParseFolder(targetFrameworkToCheck),
36 | (directoryInfo) => NuGetFramework.ParseFolder(directoryInfo.Name));
37 |
38 | if (directory != null)
39 | {
40 | break;
41 | }
42 | }
43 |
44 | if (directory is null)
45 | {
46 | return null;
47 | }
48 |
49 | return directory.EnumerateFiles("*.dll", SearchOption.AllDirectories).Select(i => GetAssemblyName(directory, i)).Where(i => i.HasValue).Select(i => i!.Value);
50 |
51 | PackageAssembly? GetAssemblyName(DirectoryInfo rootDirectory, FileInfo file)
52 | {
53 | AssemblyName assemblyName;
54 |
55 | try
56 | {
57 | assemblyName = AssemblyNameCache.GetAssemblyName(file.FullName);
58 | }
59 | catch (Exception)
60 | {
61 | return null;
62 | }
63 |
64 | string subdirectory = string.Equals(file.DirectoryName, rootDirectory.FullName, StringComparison.OrdinalIgnoreCase)
65 | ? string.Empty
66 | : file.DirectoryName!.Substring(rootDirectory.FullName.Length + 1);
67 |
68 | return new PackageAssembly(file.FullName, subdirectory, assemblyName);
69 | }
70 | }
71 | }
72 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/PackageIdentity.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Diagnostics;
8 |
9 | namespace AssemblyShader
10 | {
11 | ///
12 | /// Represents a NuGet package's identity.
13 | ///
14 | [DebuggerDisplay("{Id,nq}/{Version,nq}")]
15 | internal readonly record struct PackageIdentity : IEqualityComparer, IEquatable
16 | {
17 | ///
18 | /// Initializes a new instance of the struct with the specified ID and version.
19 | ///
20 | /// The ID of the package.
21 | /// The version of the package.
22 | /// or are .
23 | public PackageIdentity(string id, string version)
24 | {
25 | Id = id.ThrowIfNull(nameof(id)).Trim();
26 | Version = version.ThrowIfNull(nameof(version)).Trim();
27 | }
28 |
29 | ///
30 | /// Gets the ID of the package.
31 | ///
32 | public readonly string Id { get; }
33 |
34 | ///
35 | /// Gets the version of the package.
36 | ///
37 | public readonly string Version { get; }
38 |
39 | public bool Equals(PackageIdentity x, PackageIdentity y) => string.Equals(x.Id, y.Id, StringComparison.OrdinalIgnoreCase) && string.Equals(x.Version, y.Version, StringComparison.OrdinalIgnoreCase);
40 |
41 | public int GetHashCode(PackageIdentity obj)
42 | {
43 | #if NETSTANDARD
44 | return Id.GetHashCode() ^ Version.GetHashCode();
45 | #else
46 | return HashCode.Combine(obj.Id, obj.Version);
47 | #endif
48 | }
49 |
50 | public override string ToString()
51 | {
52 | return $"{Id}/{Version}";
53 | }
54 | }
55 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/README.md:
--------------------------------------------------------------------------------
1 | # .NET Assembly Shader
2 | A .NET assembly shader for allowing .NET apps to load multiple versions of the same assembly.
3 |
4 | ## Shading Transitive Dependencies
5 | This package includes build logic to rename assemblies in your dependency graph that would otherwise be unified by the .NET SDK. Consider the following project's dependency graph:
6 |
7 | ```xml
8 |
9 |
10 |
11 |
12 |
13 |
14 | ```
15 |
16 | When `PackageA` and `PackageB` are restored, `PackageZ` version `2.0.0` will be used since it is the highest resolved version in the dependency graph. At runtime, `PackageA` will be forced to use `PackageZ` version `2.0.0`
17 | even if it was built and tested against `PackageZ` version `1.0.0`. If there have been any breaking runtime changes in `PackageZ`, `PackageA` could fail at runtime. Since only one version of `PackageZ` can exist in the application
18 | directory, it can be difficult to workaround the issue.
19 |
20 | On .NET Framework, you can place `PackageZ.dll` version `1.0.0.0` into a subfolder of the application directory and use assembly binding information in the `App.config` to tell the runtime where to find it. This will only work
21 | if the assembly is strong name signed however, since the .NET assembly loader can only load different versions of the same assembly side-by-side if they are strong named signed.
22 |
23 | On .NET Core, there is no way to work around this issue. The .NET assembly loader will always load the highest version of an assembly. The only path forward is to recompile `PackageA` against `PackageZ` version `2.0.0.0`
24 | which is not always possible.
25 |
26 | Assembly shading provides an escape hatch for the above example. It renames the `PackageZ` version `1.0.0` assembly so it can exist in the same directory as `PackageZ` version `2.0.0` and updates any assemblies that reference it.
27 |
28 | ```xml
29 |
30 |
31 |
32 |
33 |
34 |
35 | ```
36 |
37 | As the project is built, the package shader logic finds the assemblies in `PackageZ` version `1.0.0` and renames them. The renamed assembly is then copied to the application output directory.
38 |
39 | Now the output folder has both `PackageZ.dll` which is version `2.0.0.0` and `PackageZ.1.0.0.0.dll`.
40 |
41 | 
42 |
43 | `PackageA.dll` was also updated to reference `PackageZ.1.0.0.0.dll` instead of `PackageZ.dll`.
44 |
45 | 
46 |
47 | ## Shading Entire Packages
48 | If you wish to shade all of the assemblies in a particular package and its transitive dependencies, you can use the `Shade` property:
49 | ```xml
50 |
51 |
52 |
53 | ```
54 | 
55 | 
56 |
57 | ## Shading Assemblies Eclipsed by Explicit Package References
58 | When you have specified a newer version of a transitive dependency in your project, NuGet will eclipse this transitive version and as a performance optimization not download it. This means that the assemblies won't be available in the global packages folder to shade. To workaround this issue, the assembly shader will log an error indicating that you need to tell NuGet to download the dependency with a `` item.
59 |
60 | In the below example since `PackageZ` version `2.0.0` is declared explicitly, the transitive dependency of `PackageA` on `PackageZ` version `1.0.0` will be eclipsed and not made available for shading.
61 |
62 | ```xml
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 | ```
71 |
72 | You will need to specify a `` item to indicate to NuGet to still make it available:
73 | ```xml
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 | ```
84 |
85 |
86 | ## Limitations
87 | Assembly shading can be a great way to fix runtime issues with dependencies, but it does have some limitations.
88 |
89 | - Shaded assemblies are strong name signed with a new public key pair. In the process, Authenticode signatures are lost.
90 | - Since a shaded assembly is loaded side-by-side with a newer version, you will not be able to pass types around between the two versions. You will get a compile-time error if you attempt to do this. If you have to pass
91 | types around between assemblies, shading will not be possible.
92 | - Assembly references will be updated because they are easy to discover but any code that uses reflection to load types will not be updated. This includes `Assembly.Load` and `Assembly.LoadFrom`.
93 | If you have code that uses reflection to load types from a shaded assembly, you will need to update it to use the new assembly name.
94 |
--------------------------------------------------------------------------------
/src/AssemblyShader/Strings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace AssemblyShader {
12 | using System;
13 |
14 |
15 | ///
16 | /// A strongly-typed resource class, for looking up localized strings, etc.
17 | ///
18 | // This class was auto-generated by the StronglyTypedResourceBuilder
19 | // class via a tool like ResGen or Visual Studio.
20 | // To add or remove a member, edit your .ResX file then rerun ResGen
21 | // with the /str option, or rebuild your VS project.
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Strings {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Strings() {
33 | }
34 |
35 | ///
36 | /// Returns the cached ResourceManager instance used by this class.
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AssemblyShader.Strings", typeof(Strings).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// Overrides the current thread's CurrentUICulture property for all
51 | /// resource lookups using this strongly typed resource class.
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 |
63 | ///
64 | /// Looks up a localized string similar to The package "{0}/{1}" cannot be shaded because its version is eclipsed by an explicit package reference with a higher version "{2}". You must add the following item to your project: <PackageDownload Include="{0}" Version="[{1}]" />.
65 | ///
66 | internal static string Error_EclipsedPackageVersion {
67 | get {
68 | return ResourceManager.GetString("Error_EclipsedPackageVersion", resourceCulture);
69 | }
70 | }
71 |
72 | ///
73 | /// Looks up a localized string similar to The specified NuGet project assets file "{0}" does not exist. Ensure a NuGet restore completed successfully..
74 | ///
75 | internal static string Error_ProjectAssetsFileNotFound {
76 | get {
77 | return ResourceManager.GetString("Error_ProjectAssetsFileNotFound", resourceCulture);
78 | }
79 | }
80 |
81 | ///
82 | /// Looks up a localized string similar to The target framework "{0}" was not found in the NuGet project assets file "{1}". Ensure a NuGet restore completed successfully..
83 | ///
84 | internal static string Error_ProjectAssetsFileTargetFrameworkNotFound {
85 | get {
86 | return ResourceManager.GetString("Error_ProjectAssetsFileTargetFrameworkNotFound", resourceCulture);
87 | }
88 | }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/src/AssemblyShader/Strings.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | The package "{0}/{1}" cannot be shaded because its version is eclipsed by an explicit package reference with a higher version "{2}". You must add the following item to your project: <PackageDownload Include="{0}" Version="[{1}]" />
122 |
123 |
124 | The specified NuGet project assets file "{0}" does not exist. Ensure a NuGet restore completed successfully.
125 |
126 |
127 | The target framework "{0}" was not found in the NuGet project assets file "{1}". Ensure a NuGet restore completed successfully.
128 |
129 |
--------------------------------------------------------------------------------
/src/AssemblyShader/StrongNameKeyPair.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using Mono.Cecil;
6 | using System;
7 | using System.IO;
8 | using System.Linq;
9 | using System.Reflection;
10 |
11 | namespace AssemblyShader
12 | {
13 | ///
14 | /// Represents a strong name key pair for a .NET assembly.
15 | ///
16 | internal sealed class StrongNameKeyPair
17 | {
18 | private static readonly GetPublicKeyMethod GetPublicKey;
19 |
20 | static StrongNameKeyPair()
21 | {
22 | Type? cryptoServiceType = typeof(WriterParameters).Assembly.GetType("Mono.Cecil.CryptoService");
23 |
24 | if (cryptoServiceType == null)
25 | {
26 | throw new InvalidOperationException("Unable to find type Mono.Cecil.CryptoService");
27 | }
28 |
29 | MethodInfo? getPublicKeyMethodInfo = cryptoServiceType.GetMethod("GetPublicKey", BindingFlags.Static | BindingFlags.Public);
30 |
31 | if (getPublicKeyMethodInfo == null)
32 | {
33 | throw new InvalidOperationException("Unable to find method Mono.Cecil.CryptoService.GetPublicKey()");
34 | }
35 |
36 | GetPublicKey = (GetPublicKeyMethod)getPublicKeyMethodInfo.CreateDelegate(typeof(GetPublicKeyMethod));
37 | }
38 |
39 | ///
40 | /// Initializes a new instance of the class.
41 | ///
42 | /// The full path to the key file to use.
43 | /// is null or contains only whitespace.
44 | public StrongNameKeyPair(string keyPath)
45 | {
46 | if (string.IsNullOrWhiteSpace(keyPath))
47 | {
48 | throw new ArgumentNullException(nameof(keyPath));
49 | }
50 |
51 | KeyPair = File.ReadAllBytes(keyPath);
52 |
53 | WriterParameters = new WriterParameters
54 | {
55 | StrongNameKeyBlob = KeyPair,
56 | };
57 |
58 | PublicKey = GetPublicKey(WriterParameters);
59 |
60 | PublicKeyString = string.Join(string.Empty, PublicKey.Select(i => i.ToString("x2")));
61 |
62 | PublicKeyToken = GetPublicKeyToken(PublicKey);
63 |
64 | PublicKeyTokenString = string.Join(string.Empty, PublicKeyToken.Select(i => i.ToString("x2")));
65 | }
66 |
67 | private delegate byte[] GetPublicKeyMethod(WriterParameters parameters);
68 |
69 | public byte[] KeyPair { get; private set; }
70 |
71 | public byte[]? PublicKey { get; private set; }
72 |
73 | public string PublicKeyString { get; private set; }
74 |
75 | public byte[] PublicKeyToken { get; private set; }
76 |
77 | public string PublicKeyTokenString { get; private set; }
78 |
79 | public WriterParameters WriterParameters { get; private set; }
80 |
81 | private byte[] GetPublicKeyToken(byte[]? key)
82 | {
83 | if (key == null || key.Length == 0)
84 | {
85 | return Array.Empty();
86 | }
87 |
88 | Span hash = stackalloc byte[20];
89 |
90 | Sha1ForNonSecretPurposes sha1 = default;
91 | sha1.Start();
92 | sha1.Append(key);
93 | sha1.Finish(hash);
94 |
95 | byte[] publicKeyToken = new byte[8];
96 |
97 | for (int i = 0; i < publicKeyToken.Length; i++)
98 | {
99 | publicKeyToken[i] = hash[hash.Length - 1 - i];
100 | }
101 |
102 | return publicKeyToken;
103 | }
104 |
105 | internal struct Sha1ForNonSecretPurposes
106 | {
107 | private long _length;
108 | private int _pos;
109 | private uint[] _w;
110 |
111 | public void Append(byte input)
112 | {
113 | int idx = _pos >> 2;
114 | _w[idx] = (_w[idx] << 8) | input;
115 | if (++_pos == 64)
116 | {
117 | Drain();
118 | }
119 | }
120 |
121 | public void Append(ReadOnlySpan input)
122 | {
123 | foreach (byte b in input)
124 | {
125 | Append(b);
126 | }
127 | }
128 |
129 | public void Finish(Span output)
130 | {
131 | long l = _length + (8 * _pos);
132 | Append(0x80);
133 | while (_pos != 56)
134 | {
135 | Append(0x00);
136 | }
137 |
138 | Append((byte)(l >> 56));
139 | Append((byte)(l >> 48));
140 | Append((byte)(l >> 40));
141 | Append((byte)(l >> 32));
142 | Append((byte)(l >> 24));
143 | Append((byte)(l >> 16));
144 | Append((byte)(l >> 8));
145 | Append((byte)l);
146 |
147 | int end = output.Length < 20 ? output.Length : 20;
148 | for (int i = 0; i != end; i++)
149 | {
150 | uint temp = _w[80 + (i / 4)];
151 | output[i] = (byte)(temp >> 24);
152 | _w[80 + (i / 4)] = temp << 8;
153 | }
154 | }
155 |
156 | public void Start()
157 | {
158 | _w ??= new uint[85];
159 |
160 | _length = 0;
161 | _pos = 0;
162 | _w[80] = 0x67452301;
163 | _w[81] = 0xEFCDAB89;
164 | _w[82] = 0x98BADCFE;
165 | _w[83] = 0x10325476;
166 | _w[84] = 0xC3D2E1F0;
167 | }
168 |
169 | private void Drain()
170 | {
171 | for (int i = 16; i != 80; i++)
172 | {
173 | _w[i] = RotateLeft(_w[i - 3] ^ _w[i - 8] ^ _w[i - 14] ^ _w[i - 16], 1);
174 | }
175 |
176 | uint a = _w[80];
177 | uint b = _w[81];
178 | uint c = _w[82];
179 | uint d = _w[83];
180 | uint e = _w[84];
181 |
182 | for (int i = 0; i != 20; i++)
183 | {
184 | const uint k = 0x5A827999;
185 | uint f = (b & c) | ((~b) & d);
186 | uint temp = RotateLeft(a, 5) + f + e + k + _w[i];
187 | e = d;
188 | d = c;
189 | c = RotateLeft(b, 30);
190 | b = a;
191 | a = temp;
192 | }
193 |
194 | for (int i = 20; i != 40; i++)
195 | {
196 | uint f = b ^ c ^ d;
197 | const uint k = 0x6ED9EBA1;
198 | uint temp = RotateLeft(a, 5) + f + e + k + _w[i];
199 | e = d;
200 | d = c;
201 | c = RotateLeft(b, 30);
202 | b = a;
203 | a = temp;
204 | }
205 |
206 | for (int i = 40; i != 60; i++)
207 | {
208 | uint f = (b & c) | (b & d) | (c & d);
209 | const uint k = 0x8F1BBCDC;
210 | uint temp = RotateLeft(a, 5) + f + e + k + _w[i];
211 | e = d;
212 | d = c;
213 | c = RotateLeft(b, 30);
214 | b = a;
215 | a = temp;
216 | }
217 |
218 | for (int i = 60; i != 80; i++)
219 | {
220 | uint f = b ^ c ^ d;
221 | const uint k = 0xCA62C1D6;
222 | uint temp = RotateLeft(a, 5) + f + e + k + _w[i];
223 | e = d;
224 | d = c;
225 | c = RotateLeft(b, 30);
226 | b = a;
227 | a = temp;
228 | }
229 |
230 | _w[80] += a;
231 | _w[81] += b;
232 | _w[82] += c;
233 | _w[83] += d;
234 | _w[84] += e;
235 |
236 | _length += 512; // 64 bytes == 512 bits
237 | _pos = 0;
238 |
239 | uint RotateLeft(uint value, int offset) => (value << offset) | (value >> (32 - offset));
240 | }
241 | }
242 | }
243 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/Tasks/GetAssembliesToShade.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using Microsoft.Build.Framework;
6 | using Microsoft.Build.Utilities;
7 | using Mono.Cecil;
8 | using NuGet.Versioning;
9 | using System;
10 | using System.Collections.Generic;
11 | using System.Diagnostics;
12 | using System.IO;
13 | using System.Linq;
14 | using System.Reflection;
15 | using System.Threading;
16 |
17 | namespace AssemblyShader.Tasks
18 | {
19 | ///
20 | /// Represents an MSBuild task that calculates the assemblies to shade.
21 | ///
22 | public sealed class GetAssembliesToShade : Task, ICancelableTask
23 | {
24 | private static readonly char[] SplitChars = new[] { ';', ',' };
25 |
26 | private readonly IAssemblyInformationReader _assemblyInformationReader;
27 | private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
28 | private readonly IInternalsVisibleToReader _internalsVisibleToReader;
29 | private readonly INuGetProjectAssetsFileLoader _nuGetProjectAssetsFileLoader;
30 | private readonly IPackageAssemblyResolver _packageAssemblyResolver;
31 |
32 | ///
33 | /// Initializes a new instance of the class.
34 | ///
35 | public GetAssembliesToShade()
36 | : this(new NuGetProjectAssetsFileLoader(), new PackageAssemblyResolver(), new AssemblyInformationReader(), new InternalsVisibleToReader())
37 | {
38 | }
39 |
40 | internal GetAssembliesToShade(INuGetProjectAssetsFileLoader nuGetProjectAssetsFileLoader, IPackageAssemblyResolver packageAssemblyResolver, IAssemblyInformationReader assemblyInformationReader, IInternalsVisibleToReader internalsVisibleToReader)
41 | : base(Strings.ResourceManager)
42 | {
43 | _nuGetProjectAssetsFileLoader = nuGetProjectAssetsFileLoader ?? throw new ArgumentNullException(nameof(nuGetProjectAssetsFileLoader));
44 | _packageAssemblyResolver = packageAssemblyResolver ?? throw new ArgumentNullException(nameof(packageAssemblyResolver));
45 | _assemblyInformationReader = assemblyInformationReader ?? throw new ArgumentNullException(nameof(assemblyInformationReader));
46 | _internalsVisibleToReader = internalsVisibleToReader ?? throw new ArgumentNullException(nameof(internalsVisibleToReader));
47 | }
48 |
49 | ///
50 | /// Gets or sets an array of representing the assemblies to shade.
51 | ///
52 | [Output]
53 | public ITaskItem[] AssembliesToShade { get; set; } = Array.Empty();
54 |
55 | ///
56 | /// Gets or sets a value indicating whether to launch the debugger when the task is executed.
57 | ///
58 | public bool Debug { get; set; }
59 |
60 | ///
61 | /// Gets or sets an array of fallback target frameworks.
62 | ///
63 | public string[] FallbackTargetFrameworks { get; set; } = Array.Empty();
64 |
65 | ///
66 | /// Gets or sets the intermediate output path of the project.
67 | ///
68 | [Required]
69 | public string IntermediateOutputPath { get; set; } = string.Empty;
70 |
71 | ///
72 | /// Gets or sets the root path to the global NuGet package folder.
73 | ///
74 | [Required]
75 | public string NuGetPackageRoot { get; set; } = string.Empty;
76 |
77 | ///
78 | /// Gets or sets an array of objects representing the PackageDownload items.
79 | ///
80 | public ITaskItem[] PackageDownloads { get; set; } = Array.Empty();
81 |
82 | ///
83 | /// Gets or sets an array of objects representing the NuGet package references.
84 | ///
85 | [Required]
86 | public ITaskItem[] PackageReferences { get; set; } = Array.Empty();
87 |
88 | ///
89 | /// Gets or sets an array of objects representing the NuGet package versions.
90 | ///
91 | public ITaskItem[] PackageVersions { get; set; } = Array.Empty();
92 |
93 | ///
94 | /// Gets or sets the full path to the NuGet assets file.
95 | ///
96 | [Required]
97 | public string ProjectAssetsFile { get; set; } = string.Empty;
98 |
99 | ///
100 | /// Gets or sets the full path to the project directory.
101 | ///
102 | public string ProjectDirectory { get; set; } = string.Empty;
103 |
104 | ///
105 | /// Gets or sets an array of objects representing the project references.
106 | ///
107 | public ITaskItem[] ProjectReferences { get; set; } = Array.Empty();
108 |
109 | ///
110 | /// Gets or sets an array of objects representing the project references to add.
111 | ///
112 | [Output]
113 | public ITaskItem[] ProjectReferencesToAdd { get; set; } = Array.Empty();
114 |
115 | ///
116 | /// Gets or sets an array of objects representing the project references to remove.
117 | ///
118 | [Output]
119 | public ITaskItem[] ProjectReferencesToRemove { get; set; } = Array.Empty();
120 |
121 | ///
122 | /// Gets or sets an array of objects representing the reference assemblies.
123 | ///
124 | [Required]
125 | public ITaskItem[] References { get; set; } = Array.Empty();
126 |
127 | ///
128 | /// Gets or sets an array of objects representing the references to add.
129 | ///
130 | [Output]
131 | public ITaskItem[] ReferencesToAdd { get; set; } = Array.Empty();
132 |
133 | ///
134 | /// Gets or sets an array of objects representing the references to remove.
135 | ///
136 | [Output]
137 | public ITaskItem[] ReferencesToRemove { get; set; } = Array.Empty();
138 |
139 | ///
140 | /// Gets or sets the full path to the key file used to strong name sign the shaded assembly.
141 | ///
142 | [Required]
143 | public string ShadedAssemblyKeyFile { get; set; } = string.Empty;
144 |
145 | ///
146 | /// Gets or sets the target framework of the current project.
147 | ///
148 | [Required]
149 | public string TargetFramework { get; set; } = string.Empty;
150 |
151 | ///
152 | /// Gets or sets the target framework moniker of the current project.
153 | ///
154 | [Required]
155 | public string TargetFrameworkMoniker { get; set; } = string.Empty;
156 |
157 | ///
158 | public void Cancel()
159 | {
160 | _cancellationTokenSource.Cancel();
161 | }
162 |
163 | ///
164 | public override bool Execute()
165 | {
166 | if (Debug)
167 | {
168 | Debugger.Launch();
169 | }
170 |
171 | StrongNameKeyPair strongNameKeyPair = new StrongNameKeyPair(ShadedAssemblyKeyFile);
172 |
173 | NuGetProjectAssetsFile? nugetProjectAssetsFile = _nuGetProjectAssetsFileLoader.Load(ProjectDirectory, ProjectAssetsFile);
174 |
175 | if (nugetProjectAssetsFile is null)
176 | {
177 | Log.LogErrorFromResources(nameof(Strings.Error_ProjectAssetsFileNotFound), ProjectAssetsFile);
178 |
179 | return false;
180 | }
181 |
182 | if (!nugetProjectAssetsFile.TryGetValue(TargetFramework, out NuGetProjectAssetsFileSection? nugetProjectAssetsFileSection) && !nugetProjectAssetsFile.TryGetValue(TargetFrameworkMoniker, out nugetProjectAssetsFileSection))
183 | {
184 | Log.LogErrorFromResources(nameof(Strings.Error_ProjectAssetsFileTargetFrameworkNotFound), !string.IsNullOrWhiteSpace(TargetFramework) ? TargetFramework : TargetFrameworkMoniker, ProjectAssetsFile);
185 |
186 | return false;
187 | }
188 |
189 | HashSet packagesToShade = GetPackagesToShade(nugetProjectAssetsFile, nugetProjectAssetsFileSection);
190 |
191 | if (!packagesToShade.Any() || _cancellationTokenSource.IsCancellationRequested)
192 | {
193 | return !Log.HasLoggedErrors;
194 | }
195 |
196 | HashSet packageDownloads = GetPackageDownloads();
197 |
198 | foreach (PackageIdentity packageToShade in packagesToShade.TakeWhile(i => !_cancellationTokenSource.IsCancellationRequested))
199 | {
200 | if (packageDownloads.Contains(packageToShade))
201 | {
202 | continue;
203 | }
204 |
205 | KeyValuePair> eclipsedPackage = nugetProjectAssetsFileSection.Packages.FirstOrDefault(i => i.Key.Id.Equals(packageToShade.Id, StringComparison.OrdinalIgnoreCase));
206 |
207 | if (!string.Equals(eclipsedPackage.Key.Version, packageToShade.Version))
208 | {
209 | Log.LogErrorFromResources(nameof(Strings.Error_EclipsedPackageVersion), packageToShade.Id, packageToShade.Version, eclipsedPackage.Key.Version);
210 | }
211 | }
212 |
213 | if (Log.HasLoggedErrors || _cancellationTokenSource.IsCancellationRequested)
214 | {
215 | return _cancellationTokenSource.IsCancellationRequested;
216 | }
217 |
218 | List assembliesToRename = GetAssembliesToShadeForPackages(strongNameKeyPair, packagesToShade, nugetProjectAssetsFile);
219 |
220 | if (!assembliesToRename.Any() || _cancellationTokenSource.IsCancellationRequested)
221 | {
222 | return !Log.HasLoggedErrors;
223 | }
224 |
225 | AddAssembliesWithReferencesToUpdate(strongNameKeyPair, assembliesToRename);
226 |
227 | SetOutputParameters(assembliesToRename);
228 |
229 | return !Log.HasLoggedErrors;
230 | }
231 |
232 | private void AddAssembliesWithReferencesToUpdate(StrongNameKeyPair strongNameKeyPair, List assembliesToRename)
233 | {
234 | AssemblyInformation assemblyInformation = _assemblyInformationReader.GetAssemblyInformation(References.Select(i => i.GetMetadata(ItemMetadataNames.FullPath)));
235 |
236 | Stack stack = new Stack(assembliesToRename);
237 |
238 | while (stack.Any())
239 | {
240 | AssemblyToRename value = stack.Pop();
241 |
242 | if (!assemblyInformation.AssemblyReferences.TryGetValue(value.AssemblyName.FullName, out List? assemblyReferences))
243 | {
244 | continue;
245 | }
246 |
247 | foreach (AssemblyReference assemblyReference in assemblyReferences)
248 | {
249 | if (!assemblyInformation.AssemblyReferences.ContainsKey(assemblyReference.Name.FullName))
250 | {
251 | continue;
252 | }
253 |
254 | if (assembliesToRename.Any(i => string.Equals(i.AssemblyName.FullName, assemblyReference.Name.FullName)))
255 | {
256 | continue;
257 | }
258 |
259 | AssemblyToRename assemblyToRename = new AssemblyToRename(assemblyReference.FullPath, assemblyReference.Name)
260 | {
261 | ShadedAssemblyName = new AssemblyNameDefinition(assemblyReference.Name.Name, assemblyReference.Name.Version)
262 | {
263 | Culture = assemblyReference.Name.CultureName,
264 | PublicKey = strongNameKeyPair.PublicKey,
265 | },
266 | ShadedPath = Path.GetFullPath(Path.Combine(IntermediateOutputPath, "ShadedAssemblies", Path.GetFileName(assemblyReference.FullPath))),
267 | };
268 |
269 | assemblyToRename.InternalsVisibleTo = _internalsVisibleToReader.Read(assemblyReference.FullPath);
270 | assemblyToRename.ShadedInternalsVisibleTo = $"{assemblyToRename.ShadedAssemblyName.Name}, PublicKey={strongNameKeyPair.PublicKeyString}";
271 |
272 | assembliesToRename.Add(assemblyToRename);
273 |
274 | stack.Push(assemblyToRename);
275 |
276 | assembliesToRename.AddRange(GetResourceAssemblies(strongNameKeyPair, assemblyToRename));
277 | }
278 | }
279 |
280 | List assembliesWithInternalsVisibleTo = new List();
281 |
282 | HashSet assembliesToUpdate = new HashSet(StringComparer.OrdinalIgnoreCase);
283 |
284 | foreach (AssemblyToRename existingAssemblyToRename in assembliesToRename)
285 | {
286 | if (existingAssemblyToRename.InternalsVisibleTo != null && assemblyInformation.FriendAssemblies.TryGetValue(existingAssemblyToRename.InternalsVisibleTo, out List? friendAssemblies))
287 | {
288 | foreach (AssemblyReference assemblyReference in friendAssemblies)
289 | {
290 | if (assembliesToRename.Any(i => i.AssemblyName.FullName.Equals(assemblyReference.Name.FullName)))
291 | {
292 | continue;
293 | }
294 |
295 | AssemblyName assemblyName = AssemblyNameCache.GetAssemblyName(assemblyReference.FullPath);
296 |
297 | if (!assembliesToUpdate.Add(assemblyName.FullName))
298 | {
299 | continue;
300 | }
301 |
302 | AssemblyToRename assemblyToRename = new AssemblyToRename(assemblyReference.FullPath, assemblyName)
303 | {
304 | ShadedAssemblyName = new AssemblyNameDefinition(assemblyName.Name, assemblyName.Version)
305 | {
306 | Culture = assemblyName.CultureName,
307 | PublicKey = strongNameKeyPair.PublicKey,
308 | },
309 | ShadedPath = Path.GetFullPath(Path.Combine(IntermediateOutputPath, "ShadedAssemblies", Path.GetFileName(assemblyReference.FullPath))),
310 | };
311 |
312 | assemblyToRename.InternalsVisibleTo = _internalsVisibleToReader.Read(assemblyReference.FullPath);
313 | assemblyToRename.ShadedInternalsVisibleTo = $"{assemblyToRename.ShadedAssemblyName.Name}, PublicKey={strongNameKeyPair.PublicKeyString}";
314 |
315 | assembliesWithInternalsVisibleTo.Add(assemblyToRename);
316 | }
317 | }
318 | }
319 |
320 | foreach (AssemblyToRename item in assembliesWithInternalsVisibleTo)
321 | {
322 | assembliesToRename.Add(item);
323 | }
324 | }
325 |
326 | private List GetAssembliesToShadeForPackages(StrongNameKeyPair strongNameKeyPair, HashSet packagesToShade, NuGetProjectAssetsFile assetsFile)
327 | {
328 | HashSet assemblyNames = new HashSet();
329 |
330 | List assembliesToRename = new List();
331 |
332 | foreach (PackageIdentity packageToShade in packagesToShade)
333 | {
334 | if (packageToShade.Id != null)
335 | {
336 | IEnumerable? packageAssemblies = _packageAssemblyResolver.GetNearest(packageToShade, NuGetPackageRoot, TargetFramework, FallbackTargetFrameworks);
337 |
338 | if (packageAssemblies == null)
339 | {
340 | KeyValuePair projectReference = assetsFile.ProjectReferences.FirstOrDefault(i => i.Value.Equals(packageToShade));
341 |
342 | if (projectReference.Key is null)
343 | {
344 | continue;
345 | }
346 |
347 | ITaskItem? projectReferenceItem = References.FirstOrDefault(i => string.Equals(i.GetMetadata(ItemMetadataNames.MSBuildSourceProjectFile), projectReference.Key));
348 |
349 | if (projectReferenceItem == null)
350 | {
351 | continue;
352 | }
353 |
354 | string assemblyPath = projectReferenceItem.GetMetadata(ItemMetadataNames.FullPath);
355 |
356 | packageAssemblies = new List(capacity: 1)
357 | {
358 | new PackageAssembly(assemblyPath, subDirectory: string.Empty, AssemblyNameCache.GetAssemblyName(assemblyPath)),
359 | };
360 | }
361 |
362 | foreach (PackageAssembly packageAssembly in packageAssemblies)
363 | {
364 | if (!assemblyNames.Add(packageAssembly.Name.FullName))
365 | {
366 | continue;
367 | }
368 |
369 | AssemblyToRename assemblyToRename = new AssemblyToRename(packageAssembly.Path, packageAssembly.Name)
370 | {
371 | DestinationSubdirectory = string.IsNullOrWhiteSpace(packageAssembly.Subdirectory) ? string.Empty : packageAssembly.Subdirectory + Path.DirectorySeparatorChar,
372 | };
373 |
374 | string assemblyName = $"{assemblyToRename.AssemblyName.Name}.{assemblyToRename.AssemblyName.Version}";
375 |
376 | assemblyToRename.ShadedAssemblyName = new AssemblyNameDefinition(assemblyName, assemblyToRename.AssemblyName.Version)
377 | {
378 | Culture = assemblyToRename.AssemblyName.CultureName,
379 | PublicKey = strongNameKeyPair.PublicKey,
380 | };
381 |
382 | assemblyToRename.InternalsVisibleTo = _internalsVisibleToReader.Read(packageAssembly.Path);
383 | assemblyToRename.ShadedInternalsVisibleTo = $"{assemblyToRename.ShadedAssemblyName.Name}, PublicKey={strongNameKeyPair.PublicKeyString}";
384 | assemblyToRename.ShadedPath = Path.GetFullPath(Path.Combine(IntermediateOutputPath, "ShadedAssemblies", packageAssembly.Subdirectory ?? string.Empty, $"{assemblyName}.dll"));
385 |
386 | assembliesToRename.Add(assemblyToRename);
387 | }
388 | }
389 | }
390 |
391 | return assembliesToRename;
392 | }
393 |
394 | private HashSet GetPackageDownloads()
395 | {
396 | HashSet packageDownloads = new HashSet();
397 |
398 | foreach (ITaskItem item in PackageDownloads)
399 | {
400 | string id = item.ItemSpec;
401 | string version = item.GetMetadata("Version");
402 |
403 | if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(version))
404 | {
405 | continue;
406 | }
407 |
408 | PackageIdentity package = new PackageIdentity(id, version.Trim().Trim('[', ']'));
409 |
410 | packageDownloads.Add(package);
411 | }
412 |
413 | return packageDownloads;
414 | }
415 |
416 | private HashSet GetPackagesToShade(NuGetProjectAssetsFile assetsFile, NuGetProjectAssetsFileSection assetsFileSection)
417 | {
418 | HashSet packagesToShade = new();
419 |
420 | Dictionary? packageVersions = PackageVersions != null && PackageVersions.Any() ? PackageVersions.ToDictionary(i => i.ItemSpec, i => i.GetMetadata(ItemMetadataNames.Version), StringComparer.OrdinalIgnoreCase) : null;
421 |
422 | foreach (ITaskItem packageReference in PackageReferences.TakeWhile(_ => !_cancellationTokenSource.IsCancellationRequested))
423 | {
424 | string shadeDependencies = packageReference.GetMetadata(ItemMetadataNames.ShadeDependencies);
425 | string shade = packageReference.GetMetadata(ItemMetadataNames.Shade);
426 |
427 | if (string.IsNullOrWhiteSpace(shade) && string.IsNullOrWhiteSpace(shadeDependencies))
428 | {
429 | continue;
430 | }
431 |
432 | PackageIdentity packageIdentity = new PackageIdentity(packageReference.ItemSpec, GetPackageVersion(packageReference, packageVersions));
433 |
434 | if (string.Equals(shade, bool.TrueString, StringComparison.OrdinalIgnoreCase))
435 | {
436 | packagesToShade.Add(packageIdentity);
437 | }
438 |
439 | if (!string.IsNullOrWhiteSpace(shadeDependencies))
440 | {
441 | if (assetsFileSection.Packages.TryGetValue(packageIdentity, out HashSet? dependencies))
442 | {
443 | foreach (string shadeDependency in shadeDependencies.Split(SplitChars, StringSplitOptions.RemoveEmptyEntries))
444 | {
445 | PackageIdentity packageToShade = dependencies.FirstOrDefault(i => string.Equals(i.Id, shadeDependency, StringComparison.OrdinalIgnoreCase));
446 |
447 | if (packageToShade.Id is not null)
448 | {
449 | packagesToShade.Add(packageToShade);
450 | }
451 | }
452 | }
453 | }
454 | }
455 |
456 | if (ProjectReferences == null)
457 | {
458 | return packagesToShade;
459 | }
460 |
461 | foreach (ITaskItem packageReference in ProjectReferences.TakeWhile(_ => !_cancellationTokenSource.IsCancellationRequested))
462 | {
463 | string shadeDependencies = packageReference.GetMetadata(ItemMetadataNames.ShadeDependencies);
464 | string shade = packageReference.GetMetadata(ItemMetadataNames.Shade);
465 |
466 | if (string.IsNullOrWhiteSpace(shade) && string.IsNullOrWhiteSpace(shadeDependencies))
467 | {
468 | continue;
469 | }
470 |
471 | string fullPath = packageReference.GetMetadata("FullPath");
472 |
473 | if (!assetsFile.ProjectReferences.TryGetValue(fullPath, out PackageIdentity packageIdentity))
474 | {
475 | continue;
476 | }
477 |
478 | if (string.Equals(shade, bool.TrueString, StringComparison.OrdinalIgnoreCase))
479 | {
480 | packagesToShade.Add(packageIdentity);
481 | }
482 |
483 | if (!string.IsNullOrWhiteSpace(shadeDependencies))
484 | {
485 | if (assetsFileSection.Packages.TryGetValue(packageIdentity, out HashSet? dependencies))
486 | {
487 | if (shadeDependencies == "*")
488 | {
489 | foreach (PackageIdentity item in dependencies)
490 | {
491 | packagesToShade.Add(item);
492 | }
493 | }
494 | else
495 | {
496 | foreach (string shadeDependency in shadeDependencies.Split(SplitChars, StringSplitOptions.RemoveEmptyEntries))
497 | {
498 | PackageIdentity packageToShade = dependencies.FirstOrDefault(i => string.Equals(i.Id, shadeDependency, StringComparison.OrdinalIgnoreCase));
499 |
500 | packagesToShade.Add(packageToShade);
501 | }
502 | }
503 | }
504 | }
505 | }
506 |
507 | return packagesToShade;
508 |
509 | string GetPackageVersion(ITaskItem packageReference, Dictionary? packageVersions)
510 | {
511 | string? packageVersion = packageReference.GetMetadata(ItemMetadataNames.Version);
512 |
513 | if (!string.IsNullOrEmpty(packageVersion))
514 | {
515 | return packageVersion;
516 | }
517 |
518 | packageVersion = packageReference.GetMetadata(ItemMetadataNames.VersionOverride);
519 |
520 | if (!string.IsNullOrEmpty(packageVersion))
521 | {
522 | return packageVersion;
523 | }
524 |
525 | if (packageVersions != null && packageVersions.TryGetValue(packageReference.ItemSpec, out packageVersion))
526 | {
527 | return packageVersion;
528 | }
529 |
530 | return string.Empty;
531 | }
532 | }
533 |
534 | private IEnumerable GetResourceAssemblies(StrongNameKeyPair strongNameKeyPair, AssemblyToRename assemblyToRename)
535 | {
536 | FileInfo assemblyFile = new FileInfo(assemblyToRename.FullPath);
537 |
538 | if (!assemblyFile.Exists)
539 | {
540 | yield break;
541 | }
542 |
543 | foreach (FileInfo resourceAssemblyFile in Directory.EnumerateFiles(assemblyFile.DirectoryName!, Path.ChangeExtension(assemblyFile.Name, ".resources.dll"), SearchOption.AllDirectories).Select(i => new FileInfo(i)).TakeWhile(_ => !_cancellationTokenSource.IsCancellationRequested))
544 | {
545 | string subdirectory = string.Equals(resourceAssemblyFile.DirectoryName, assemblyFile.DirectoryName, StringComparison.OrdinalIgnoreCase)
546 | ? string.Empty
547 | : resourceAssemblyFile.DirectoryName!.Substring(assemblyFile.DirectoryName!.Length + 1) + Path.DirectorySeparatorChar;
548 |
549 | AssemblyName resourceAssemblyName = AssemblyNameCache.GetAssemblyName(resourceAssemblyFile.FullName);
550 |
551 | yield return new AssemblyToRename(resourceAssemblyFile.FullName, resourceAssemblyName)
552 | {
553 | ShadedAssemblyName = new AssemblyNameDefinition(resourceAssemblyName.Name, resourceAssemblyName.Version)
554 | {
555 | Culture = resourceAssemblyName.CultureName,
556 | PublicKey = strongNameKeyPair.PublicKey,
557 | },
558 | ShadedPath = Path.GetFullPath(Path.Combine(IntermediateOutputPath, "ShadedAssemblies", subdirectory, resourceAssemblyFile.Name)),
559 | DestinationSubdirectory = subdirectory,
560 | };
561 | }
562 | }
563 |
564 | private void SetOutputParameters(IReadOnlyCollection assembliesToRename)
565 | {
566 | List assembliesToShade = new List(assembliesToRename.Count);
567 | List referencesToRemove = new List(assembliesToRename.Count);
568 | List referencesToAdd = new List(assembliesToRename.Count);
569 | List projectReferencesToAdd = new List(assembliesToRename.Count);
570 | List projectReferencesToRemove = new List(assembliesToRename.Count);
571 |
572 | Dictionary> existingReferenceItems = GetItemsByAssemblyName(References);
573 |
574 | foreach (AssemblyToRename assemblyToRename in assembliesToRename.TakeWhile(_ => !_cancellationTokenSource.IsCancellationRequested))
575 | {
576 | TaskItem assemblyToShade = new TaskItem(Path.GetFullPath(assemblyToRename.ShadedPath!), assemblyToRename.Metadata);
577 |
578 | assemblyToShade.SetMetadata(ItemMetadataNames.OriginalPath, assemblyToRename.FullPath);
579 | assemblyToShade.SetMetadata(ItemMetadataNames.ShadedAssemblyName, assemblyToRename.ShadedAssemblyName!.FullName);
580 | assemblyToShade.SetMetadata(ItemMetadataNames.AssemblyName, assemblyToRename.AssemblyName.FullName);
581 | assemblyToShade.SetMetadata(ItemMetadataNames.InternalsVisibleTo, assemblyToRename.InternalsVisibleTo);
582 | assemblyToShade.SetMetadata(ItemMetadataNames.ShadedInternalsVisibleTo, assemblyToRename.ShadedInternalsVisibleTo);
583 |
584 | assemblyToShade.SetMetadata(ItemMetadataNames.DestinationSubdirectory, string.IsNullOrWhiteSpace(assemblyToRename.DestinationSubdirectory) ? string.Empty : assemblyToRename.DestinationSubdirectory);
585 |
586 | bool isProjectReference = false;
587 |
588 | if (existingReferenceItems.TryGetValue(assemblyToRename.AssemblyName.FullName, out List? existingReferenceItemsForAssembly))
589 | {
590 | foreach (ITaskItem existingReferenceItemForAssembly in existingReferenceItemsForAssembly)
591 | {
592 | if (string.Equals(existingReferenceItemForAssembly.GetMetadata("ReferenceSourceTarget"), "ProjectReference", StringComparison.OrdinalIgnoreCase))
593 | {
594 | isProjectReference = true;
595 |
596 | TaskItem projectReferenceToRemove = new TaskItem(existingReferenceItemForAssembly.ItemSpec);
597 |
598 | projectReferencesToRemove.Add(projectReferenceToRemove);
599 |
600 | continue;
601 | }
602 |
603 | TaskItem referenceToRemove = new TaskItem(existingReferenceItemForAssembly.ItemSpec);
604 |
605 | referencesToRemove.Add(referenceToRemove);
606 | }
607 |
608 | if (isProjectReference)
609 | {
610 | TaskItem projectReferenceToAdd = new TaskItem(assemblyToRename.ShadedPath, existingReferenceItemsForAssembly.First().CloneCustomMetadata());
611 |
612 | projectReferencesToAdd.Add(projectReferenceToAdd);
613 | }
614 | else
615 | {
616 | TaskItem referenceToAdd = new TaskItem(assemblyToRename.ShadedPath, existingReferenceItemsForAssembly.First().CloneCustomMetadata());
617 |
618 | referenceToAdd.SetMetadata(ItemMetadataNames.HintPath, assemblyToRename.ShadedPath);
619 | referenceToAdd.SetMetadata(ItemMetadataNames.OriginalPath, assemblyToRename.FullPath);
620 |
621 | referencesToAdd.Add(referenceToAdd);
622 | }
623 | }
624 |
625 | assembliesToShade.Add(assemblyToShade);
626 | }
627 |
628 | AssembliesToShade = assembliesToShade.ToArray();
629 | ReferencesToAdd = referencesToAdd.ToArray();
630 | ReferencesToRemove = referencesToRemove.ToArray();
631 | ProjectReferencesToAdd = projectReferencesToAdd.ToArray();
632 | ProjectReferencesToRemove = projectReferencesToRemove.ToArray();
633 |
634 | Dictionary> GetItemsByAssemblyName(IEnumerable items)
635 | {
636 | Dictionary> existingReferenceItems = new Dictionary>(StringComparer.OrdinalIgnoreCase);
637 |
638 | foreach (ITaskItem referenceItem in items)
639 | {
640 | if (!File.Exists(referenceItem.ItemSpec))
641 | {
642 | continue;
643 | }
644 |
645 | AssemblyName assemblyName = AssemblyNameCache.GetAssemblyName(referenceItem.ItemSpec);
646 |
647 | if (!existingReferenceItems.TryGetValue(assemblyName.FullName, out List? references))
648 | {
649 | references = new List();
650 |
651 | existingReferenceItems.Add(assemblyName.FullName, references);
652 | }
653 |
654 | references.Add(referenceItem);
655 | }
656 |
657 | return existingReferenceItems;
658 | }
659 | }
660 | }
661 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/Tasks/ShadeAssemblies.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using Microsoft.Build.Framework;
6 | using Microsoft.Build.Utilities;
7 | using Mono.Cecil;
8 | using System;
9 | using System.Collections.Generic;
10 | using System.Diagnostics;
11 | using System.IO;
12 | using System.Linq;
13 | using System.Reflection;
14 | using System.Threading;
15 |
16 | namespace AssemblyShader.Tasks
17 | {
18 | ///
19 | /// Represents an MSBuild task that shades assemblies.
20 | ///
21 | public sealed class ShadeAssemblies : Task, ICancelableTask
22 | {
23 | private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
24 |
25 | ///
26 | /// Gets or sets an array of objects representing the assemblies to shade.
27 | ///
28 | [Required]
29 | public ITaskItem[]? AssembliesToShade { get; set; }
30 |
31 | ///
32 | /// Gets or sets a value indicating whether the debugger should be launched when the task is executed.
33 | ///
34 | public bool Debug { get; set; }
35 |
36 | ///
37 | /// Gets or sets the full path to the key file used to sign shaded assemblies.
38 | ///
39 | [Required]
40 | public string? ShadedAssemblyKeyFile { get; set; }
41 |
42 | ///
43 | public void Cancel()
44 | {
45 | _cancellationTokenSource.Cancel();
46 | }
47 |
48 | ///
49 | public override bool Execute()
50 | {
51 | if (Debug)
52 | {
53 | Debugger.Launch();
54 | }
55 |
56 | if (ShadedAssemblyKeyFile is null || AssembliesToShade is null)
57 | {
58 | return false;
59 | }
60 |
61 | StrongNameKeyPair strongNameKeyPair = new StrongNameKeyPair(ShadedAssemblyKeyFile);
62 |
63 | Dictionary newAssemblyNames = AssembliesToShade.ToDictionary(i => i.GetMetadata(ItemMetadataNames.AssemblyName), i => new AssemblyName(i.GetMetadata(ItemMetadataNames.ShadedAssemblyName)), StringComparer.OrdinalIgnoreCase);
64 |
65 | Dictionary internalsVisibleTo = GetInternalsVisibleTo();
66 |
67 | foreach (ITaskItem assemblyToShade in AssembliesToShade.TakeWhile(_ => !_cancellationTokenSource.IsCancellationRequested))
68 | {
69 | FileInfo assemblyPath = new FileInfo(assemblyToShade.GetMetadata(ItemMetadataNames.OriginalPath));
70 | FileInfo shadedAssemblyPath = new FileInfo(assemblyToShade.ItemSpec);
71 |
72 | AssemblyName shadedAssemblyName = new AssemblyName(assemblyToShade.GetMetadata(ItemMetadataNames.ShadedAssemblyName));
73 |
74 | using (DefaultAssemblyResolver resolver = new DefaultAssemblyResolver())
75 | {
76 | resolver.AddSearchDirectory(assemblyPath.DirectoryName);
77 |
78 | bool symbolsExist = File.Exists(Path.ChangeExtension(assemblyPath.FullName, ".pdb"));
79 |
80 | using (AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(assemblyPath.FullName, new ReaderParameters
81 | {
82 | AssemblyResolver = resolver,
83 | ReadSymbols = File.Exists(Path.ChangeExtension(assemblyPath.FullName, ".pdb")),
84 | }))
85 | {
86 | string previousAssemblyName = assembly.Name.FullName;
87 |
88 | Directory.CreateDirectory(shadedAssemblyPath.DirectoryName!);
89 |
90 | List newAttributes = new List(assembly.CustomAttributes.Count);
91 |
92 | assembly.Name.Name = shadedAssemblyName.Name;
93 |
94 | assembly.MainModule.Attributes &= ~ModuleAttributes.StrongNameSigned;
95 |
96 | Log.LogMessageFromText($"Shading assembly {assemblyPath.FullName} => {shadedAssemblyPath.FullName}", MessageImportance.Normal);
97 | Log.LogMessageFromText($" Name: {previousAssemblyName} => {shadedAssemblyName.FullName}", MessageImportance.Normal);
98 |
99 | foreach (AssemblyNameReference assemblyReference in assembly.MainModule.AssemblyReferences)
100 | {
101 | if (newAssemblyNames.TryGetValue(assemblyReference.FullName, out AssemblyName? shadedReferenceAssemblyName))
102 | {
103 | Log.LogMessageFromText($" Reference: {assemblyReference.FullName} -> {shadedReferenceAssemblyName.FullName}", MessageImportance.Normal);
104 |
105 | assemblyReference.Name = shadedReferenceAssemblyName.Name;
106 | assemblyReference.PublicKeyToken = strongNameKeyPair.PublicKeyToken;
107 | }
108 | }
109 |
110 | foreach (CustomAttribute customAttribute in assembly.CustomAttributes)
111 | {
112 | switch (customAttribute.AttributeType.FullName)
113 | {
114 | case "System.Runtime.CompilerServices.InternalsVisibleToAttribute":
115 | if (customAttribute.ConstructorArguments[0].Value is string internalsVisibleToAttributeConstructorArgument && internalsVisibleTo.TryGetValue(internalsVisibleToAttributeConstructorArgument, out string? value))
116 | {
117 | Log.LogMessageFromText($" InternalsVisibleTo: {value}", MessageImportance.Normal);
118 |
119 | CustomAttribute attribute = new CustomAttribute(customAttribute.Constructor);
120 | attribute.ConstructorArguments.Add(new CustomAttributeArgument(customAttribute.ConstructorArguments[0].Type, value));
121 | newAttributes.Add(attribute);
122 | }
123 |
124 | break;
125 |
126 | case "System.Runtime.Versioning.TargetFrameworkAttribute":
127 | if (customAttribute.ConstructorArguments[0].Value is string targetFrameworkAttributeConstructorArgument && DotNetAssemblyResolver.TryGetReferenceAssemblyPath(targetFrameworkAttributeConstructorArgument, out string? referenceAssemblyDirectory))
128 | {
129 | resolver.AddSearchDirectory(referenceAssemblyDirectory);
130 | }
131 |
132 | break;
133 | }
134 | }
135 |
136 | foreach (CustomAttribute item in newAttributes)
137 | {
138 | assembly.CustomAttributes.Add(item);
139 | }
140 |
141 | try
142 | {
143 | assembly.Write(
144 | shadedAssemblyPath.FullName,
145 | new WriterParameters
146 | {
147 | StrongNameKeyBlob = strongNameKeyPair.KeyPair,
148 | WriteSymbols = symbolsExist,
149 | });
150 | }
151 | catch (Exception e)
152 | {
153 | Log.LogError("Failed to write assembly '{0}'", shadedAssemblyPath.FullName);
154 |
155 | Log.LogErrorFromException(e);
156 | }
157 | }
158 | }
159 |
160 | AssemblyName assemblyName = AssemblyName.GetAssemblyName(shadedAssemblyPath.FullName);
161 | }
162 |
163 | return !Log.HasLoggedErrors;
164 | }
165 |
166 | private Dictionary GetInternalsVisibleTo()
167 | {
168 | if (AssembliesToShade is null)
169 | {
170 | return new Dictionary(capacity: 0);
171 | }
172 |
173 | Dictionary internalsVisibleToDictionary = new Dictionary(StringComparer.OrdinalIgnoreCase);
174 |
175 | foreach (ITaskItem assemblyToShadeItem in AssembliesToShade)
176 | {
177 | string internalsVisibleTo = assemblyToShadeItem.GetMetadata(ItemMetadataNames.InternalsVisibleTo);
178 | string shadedInternsVisibleTo = assemblyToShadeItem.GetMetadata(ItemMetadataNames.ShadedInternalsVisibleTo);
179 |
180 | if (!string.IsNullOrWhiteSpace(internalsVisibleTo) && !string.IsNullOrWhiteSpace(shadedInternsVisibleTo))
181 | {
182 | internalsVisibleToDictionary[internalsVisibleTo] = shadedInternsVisibleTo;
183 | }
184 | }
185 |
186 | return internalsVisibleToDictionary;
187 | }
188 | }
189 | }
--------------------------------------------------------------------------------
/src/AssemblyShader/build/AssemblyShader.Common.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 | $(MSBuildThisFileDirectory)shaded.snk
4 |
5 |
6 |
7 | $(TargetsForTfmSpecificContentInPackage);GetAssembliesToShade
8 |
9 |
10 |
13 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 | <_ResolvedProjectReferencePaths Remove="@(_ProjectReferencesToRemove)" />
46 | <_ResolvedProjectReferencePaths Include="@(_ProjectReferencesToAdd)" />
47 |
48 |
54 |
55 |
56 |
57 |
63 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/src/AssemblyShader/build/AssemblyShader.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 | $(MSBuildThisFileDirectory)net472\AssemblyShader.dll
4 | $(MSBuildThisFileDirectory)netstandard2.0\AssemblyShader.dll
5 |
6 |
7 |
9 |
10 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/src/AssemblyShader/build/shaded.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffkl/AssemblyShader/f289db121a8541219b93c0afd051b65017427846/src/AssemblyShader/build/shaded.snk
--------------------------------------------------------------------------------
/src/GlobalSuppressions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c). All rights reserved.
2 | //
3 | // Licensed under the MIT license.
4 |
5 | using System.Diagnostics.CodeAnalysis;
6 |
7 | [assembly: SuppressMessage("Style", "IDE0300:Simplify collection initialization", Justification = "Reviewed.")]
8 | [assembly: SuppressMessage("StyleCop.CSharp.NamingRules", "SA1309:FieldNamesMustNotBeginWithUnderscore", Justification = "Reviewed.")]
9 | [assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1101:PrefixLocalCallsWithThis", Justification = "Reviewed.")]
10 | [assembly: SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1000:KeywordsMustBeSpacedCorrectly", Justification = "Reviewed.")]
11 | [assembly: SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1011:Closing square brackets should be spaced correctly", Justification = "Reviewed.")]
--------------------------------------------------------------------------------
/stylecop.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
3 | "settings": {
4 | "orderingRules": {
5 | "usingDirectivesPlacement": "outsideNamespace",
6 | "systemUsingDirectivesFirst": false,
7 | "blankLinesBetweenUsingGroups": "require"
8 | },
9 | "layoutRules": {
10 | "newlineAtEndOfFile": "omit"
11 | },
12 | "documentationRules": {
13 | "companyName": "",
14 | "copyrightText": "Copyright (c). All rights reserved.\n\nLicensed under the MIT license.",
15 | "xmlHeader": false,
16 | "documentInternalElements": false
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/version.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://raw.githubusercontent.com/AArnott/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json",
3 | "version": "1.1",
4 | "assemblyVersion": "1.0",
5 | "buildNumberOffset": -1,
6 | "publicReleaseRefSpec": [
7 | "^refs/tags/v\\d+\\.\\d+\\.\\d+"
8 | ],
9 | "cloudBuild": {
10 | "buildNumber": {
11 | "enabled": true
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/xunit.runner.json:
--------------------------------------------------------------------------------
1 | {
2 | "appDomain": "denied",
3 | "shadowCopy": false
4 | }
--------------------------------------------------------------------------------