├── .github
└── workflows
│ └── main.yml
├── .gitignore
├── Directory.Build.props
├── LICENSE
├── README.md
├── SourceFileFinder.Tests
├── Cases
│ ├── ClassWithCtor.cs
│ ├── ClassWithLineHidden.cs
│ ├── ClassWithoutNamespace.cs
│ ├── EmptyClass.cs
│ ├── EmptyClassInNestedNamespace.cs
│ ├── EmptyClassWithoutNamespace.cs
│ ├── EmptyDerivedClass.cs
│ ├── NestedEmptyClass.cs
│ ├── NestedEmptyClassInNestedNamespace.cs
│ ├── OverriddenProtectedMethodClass.cs
│ ├── OverriddenPublicMethodClass.cs
│ ├── PartialClassWithMethod.1.cs
│ ├── PartialClassWithMethod.2.cs
│ ├── PrivateMethodClass.cs
│ ├── ProtectedMethodClass.cs
│ └── PublicMethodClass.cs
├── GlobalSuppressions.cs
├── RazorCases
│ ├── ComponentWithMethod.razor
│ ├── ComponentWithoutMethods.razor
│ └── _Imports.razor
├── SourceFileFinder.Tests.csproj
└── SourceFileFinderTest.cs
├── SourceFileFinder.sln
├── SourceFileFinder
├── CSharpTypeLocator.cs
├── GlobalSuppressions.cs
├── MemberInfoExtensions.cs
├── SourceFileFinder.cs
├── SourceFileFinder.csproj
├── build.targets
└── buildMultiTargeting.targets
├── global.json
├── key.snk
└── version.json
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | name: "CI/CD"
2 |
3 | on:
4 | pull_request:
5 | push:
6 | release:
7 | types:
8 | - published
9 |
10 | jobs:
11 | build-test:
12 | name: Build and test
13 | runs-on: ubuntu-latest
14 | steps:
15 | - name: Checkout Repository
16 | uses: actions/checkout@v2
17 | with:
18 | fetch-depth: 0 # avoid shallow clone so nbgv can do its work.
19 |
20 | - uses: actions/setup-dotnet@v1
21 | with:
22 | dotnet-version: '5.0.x'
23 |
24 | - uses: dotnet/nbgv@master
25 | with:
26 | setAllVars: true
27 |
28 | - name: Building and verifying library
29 | run: |
30 | dotnet build -c Debug /nowarn:CS1591 /p:UseSourceLink=true
31 | dotnet test -c Debug --no-build /nowarn:CS1591 /p:CollectCoverage=true /p:CoverletOutput=./coverage/ /p:CoverletOutputFormat=opencover /p:ExcludeByAttribute=\"Obsolete,GeneratedCodeAttribute,CompilerGeneratedAttribute\" /p:UseSourceLink=true
32 |
33 | publish-nuget-packages:
34 | if: github.event_name == 'release'
35 | needs: [build-test]
36 | runs-on: ubuntu-latest
37 | steps:
38 | - name: Checkout Repository
39 | uses: actions/checkout@v2
40 | with:
41 | fetch-depth: 0 # avoid shallow clone so nbgv can do its work.
42 |
43 | - uses: actions/setup-dotnet@v1
44 | with:
45 | dotnet-version: '5.0.x'
46 |
47 | - uses: dotnet/nbgv@master
48 | with:
49 | setAllVars: true
50 |
51 | - name: Creating library package for release
52 | run: dotnet pack -c Release -o ${GITHUB_WORKSPACE}/packages -p:RepositoryBranch=master -p:ContinuousIntegrationBuild=true /p:PublicRelease=true
53 |
54 | - name: Push packages to NuGet
55 | run: dotnet nuget push ${GITHUB_WORKSPACE}/packages/'*.nupkg' -k ${{ secrets.NUGET_KEY }} -s https://api.nuget.org/v3/index.json --skip-duplicate --no-symbols true
56 |
--------------------------------------------------------------------------------
/.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/master/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 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # TeamCity is a build add-in
131 | _TeamCity*
132 |
133 | # DotCover is a Code Coverage Tool
134 | *.dotCover
135 |
136 | # AxoCover is a Code Coverage Tool
137 | .axoCover/*
138 | !.axoCover/settings.json
139 |
140 | # Visual Studio code coverage results
141 | *.coverage
142 | *.coveragexml
143 |
144 | # NCrunch
145 | _NCrunch_*
146 | .*crunch*.local.xml
147 | nCrunchTemp_*
148 |
149 | # MightyMoose
150 | *.mm.*
151 | AutoTest.Net/
152 |
153 | # Web workbench (sass)
154 | .sass-cache/
155 |
156 | # Installshield output folder
157 | [Ee]xpress/
158 |
159 | # DocProject is a documentation generator add-in
160 | DocProject/buildhelp/
161 | DocProject/Help/*.HxT
162 | DocProject/Help/*.HxC
163 | DocProject/Help/*.hhc
164 | DocProject/Help/*.hhk
165 | DocProject/Help/*.hhp
166 | DocProject/Help/Html2
167 | DocProject/Help/html
168 |
169 | # Click-Once directory
170 | publish/
171 |
172 | # Publish Web Output
173 | *.[Pp]ublish.xml
174 | *.azurePubxml
175 | # Note: Comment the next line if you want to checkin your web deploy settings,
176 | # but database connection strings (with potential passwords) will be unencrypted
177 | *.pubxml
178 | *.publishproj
179 |
180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
181 | # checkin your Azure Web App publish settings, but sensitive information contained
182 | # in these scripts will be unencrypted
183 | PublishScripts/
184 |
185 | # NuGet Packages
186 | *.nupkg
187 | # NuGet Symbol Packages
188 | *.snupkg
189 | # The packages folder can be ignored because of Package Restore
190 | **/[Pp]ackages/*
191 | # except build/, which is used as an MSBuild target.
192 | !**/[Pp]ackages/build/
193 | # Uncomment if necessary however generally it will be regenerated when needed
194 | #!**/[Pp]ackages/repositories.config
195 | # NuGet v3's project.json files produces more ignorable files
196 | *.nuget.props
197 | *.nuget.targets
198 |
199 | # Microsoft Azure Build Output
200 | csx/
201 | *.build.csdef
202 |
203 | # Microsoft Azure Emulator
204 | ecf/
205 | rcf/
206 |
207 | # Windows Store app package directories and files
208 | AppPackages/
209 | BundleArtifacts/
210 | Package.StoreAssociation.xml
211 | _pkginfo.txt
212 | *.appx
213 | *.appxbundle
214 | *.appxupload
215 |
216 | # Visual Studio cache files
217 | # files ending in .cache can be ignored
218 | *.[Cc]ache
219 | # but keep track of directories ending in .cache
220 | !?*.[Cc]ache/
221 |
222 | # Others
223 | ClientBin/
224 | ~$*
225 | *~
226 | *.dbmdl
227 | *.dbproj.schemaview
228 | *.jfm
229 | *.pfx
230 | *.publishsettings
231 | orleans.codegen.cs
232 |
233 | # Including strong name files can present a security risk
234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235 | #*.snk
236 |
237 | # Since there are multiple workflows, uncomment next line to ignore bower_components
238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239 | #bower_components/
240 |
241 | # RIA/Silverlight projects
242 | Generated_Code/
243 |
244 | # Backup & report files from converting an old project file
245 | # to a newer Visual Studio version. Backup files are not needed,
246 | # because we have git ;-)
247 | _UpgradeReport_Files/
248 | Backup*/
249 | UpgradeLog*.XML
250 | UpgradeLog*.htm
251 | ServiceFabricBackup/
252 | *.rptproj.bak
253 |
254 | # SQL Server files
255 | *.mdf
256 | *.ldf
257 | *.ndf
258 |
259 | # Business Intelligence projects
260 | *.rdl.data
261 | *.bim.layout
262 | *.bim_*.settings
263 | *.rptproj.rsuser
264 | *- [Bb]ackup.rdl
265 | *- [Bb]ackup ([0-9]).rdl
266 | *- [Bb]ackup ([0-9][0-9]).rdl
267 |
268 | # Microsoft Fakes
269 | FakesAssemblies/
270 |
271 | # GhostDoc plugin setting file
272 | *.GhostDoc.xml
273 |
274 | # Node.js Tools for Visual Studio
275 | .ntvs_analysis.dat
276 | node_modules/
277 |
278 | # Visual Studio 6 build log
279 | *.plg
280 |
281 | # Visual Studio 6 workspace options file
282 | *.opt
283 |
284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285 | *.vbw
286 |
287 | # Visual Studio LightSwitch build output
288 | **/*.HTMLClient/GeneratedArtifacts
289 | **/*.DesktopClient/GeneratedArtifacts
290 | **/*.DesktopClient/ModelManifest.xml
291 | **/*.Server/GeneratedArtifacts
292 | **/*.Server/ModelManifest.xml
293 | _Pvt_Extensions
294 |
295 | # Paket dependency manager
296 | .paket/paket.exe
297 | paket-files/
298 |
299 | # FAKE - F# Make
300 | .fake/
301 |
302 | # CodeRush personal settings
303 | .cr/personal
304 |
305 | # Python Tools for Visual Studio (PTVS)
306 | __pycache__/
307 | *.pyc
308 |
309 | # Cake - Uncomment if you are using it
310 | # tools/**
311 | # !tools/packages.config
312 |
313 | # Tabs Studio
314 | *.tss
315 |
316 | # Telerik's JustMock configuration file
317 | *.jmconfig
318 |
319 | # BizTalk build output
320 | *.btp.cs
321 | *.btm.cs
322 | *.odx.cs
323 | *.xsd.cs
324 |
325 | # OpenCover UI analysis results
326 | OpenCover/
327 |
328 | # Azure Stream Analytics local run output
329 | ASALocalRun/
330 |
331 | # MSBuild Binary and Structured Log
332 | *.binlog
333 |
334 | # NVidia Nsight GPU debugger configuration file
335 | *.nvuser
336 |
337 | # MFractors (Xamarin productivity tool) working folder
338 | .mfractor/
339 |
340 | # Local History for Visual Studio
341 | .localhistory/
342 |
343 | # BeatPulse healthcheck temp database
344 | healthchecksdb
345 |
346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
347 | MigrationBackup/
348 |
349 | # Ionide (cross platform F# VS Code tools) working folder
350 | .ionide/
351 |
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | 9.0
4 | enable
5 | CS8600;CS8602;CS8603;CS8625
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Egil Hansen
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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Source File Finder
2 | A small helper library, that allows you to find the source file of a type at runtime, based on the debug information included in the types assembly through the related portable PDB.
3 |
4 | ```csharp
5 | var target = typeof(MyType);
6 |
7 | using var finder = new SourceFileFinder(target.Assembly);
8 |
9 | IEnumerable fileNames = finder.Find(target);
10 | ```
11 |
12 | ## Try it
13 | Download from nuget: https://www.nuget.org/packages/SourceFileFinder/
14 |
15 | ## Limitations / Issues
16 |
17 | This project forces (via an included `.targets` file) the debug settings of consuming projects to be
18 |
19 | ```
20 | true
21 | embedded
22 | ```
23 |
24 | This avoid issues with other `DebugType` settings (`none`, `full`, and `pdbonly`) that produce PDBs in the Windows format.
25 |
26 |
27 | ## Contributors
28 | Big thanks to @jnm2 and @webczat in their help prototyping this library.
29 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/ClassWithCtor.cs:
--------------------------------------------------------------------------------
1 | namespace ReflectionHelpers.Cases
2 | {
3 | public class ClassWithCtor
4 | {
5 | public ClassWithCtor()
6 | {
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/ClassWithLineHidden.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace ReflectionHelpers.Cases
8 | {
9 | public class ClassWithLineHidden
10 | {
11 | #line hidden
12 | void Foo()
13 | {
14 |
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/ClassWithoutNamespace.cs:
--------------------------------------------------------------------------------
1 | public class ClassWithoutNamespace
2 | {
3 | #pragma warning disable CA1822 // Mark members as static
4 | public void Foo() { }
5 | #pragma warning restore CA1822 // Mark members as static
6 | }
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/EmptyClass.cs:
--------------------------------------------------------------------------------
1 | namespace ReflectionHelpers.Cases
2 | {
3 | public class EmptyClass { }
4 | }
5 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/EmptyClassInNestedNamespace.cs:
--------------------------------------------------------------------------------
1 | namespace ReflectionHelpers.Cases
2 | {
3 | namespace SubCases
4 | {
5 | public class EmptyClassInNestedNamespace
6 | {
7 |
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/EmptyClassWithoutNamespace.cs:
--------------------------------------------------------------------------------
1 | public class EmptyClassWithoutNamespace
2 | {
3 | }
4 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/EmptyDerivedClass.cs:
--------------------------------------------------------------------------------
1 | namespace ReflectionHelpers.Cases
2 | {
3 | public class EmptyDerivedClass : PublicMethodClass
4 | {
5 |
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/NestedEmptyClass.cs:
--------------------------------------------------------------------------------
1 | namespace ReflectionHelpers.Cases
2 | {
3 | public class OuterClass
4 | {
5 | public class NestedEmptyClass
6 | {
7 |
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/NestedEmptyClassInNestedNamespace.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace ReflectionHelpers.Cases
8 | {
9 | namespace SubCases
10 | {
11 | public class OuterClass
12 | {
13 | public class NestedEmptyClassInNestedNamespace
14 | {
15 |
16 | }
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/OverriddenProtectedMethodClass.cs:
--------------------------------------------------------------------------------
1 | namespace ReflectionHelpers.Cases
2 | {
3 | public class OverriddenProtectedMethodClass : ProtectedMethodClass
4 | {
5 | protected override void Foo() => base.Foo();
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/OverriddenPublicMethodClass.cs:
--------------------------------------------------------------------------------
1 | namespace ReflectionHelpers.Cases
2 | {
3 | public class OverriddenPublicMethodClass : PublicMethodClass
4 | {
5 | public override void Foo() => base.Foo();
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/PartialClassWithMethod.1.cs:
--------------------------------------------------------------------------------
1 | namespace ReflectionHelpers.Cases
2 | {
3 | public partial class PartialClassWithMethod
4 | {
5 | public void Foo() { }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/PartialClassWithMethod.2.cs:
--------------------------------------------------------------------------------
1 | namespace ReflectionHelpers.Cases
2 | {
3 | public partial class PartialClassWithMethod
4 | {
5 | public void Bar()
6 | {
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/PrivateMethodClass.cs:
--------------------------------------------------------------------------------
1 | namespace ReflectionHelpers.Cases
2 | {
3 | public class PrivateMethodClass
4 | {
5 | private void Foo() { }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/ProtectedMethodClass.cs:
--------------------------------------------------------------------------------
1 | namespace ReflectionHelpers.Cases
2 | {
3 | public class ProtectedMethodClass
4 | {
5 | protected virtual void Foo() { }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/Cases/PublicMethodClass.cs:
--------------------------------------------------------------------------------
1 | namespace ReflectionHelpers.Cases
2 | {
3 | public class PublicMethodClass
4 | {
5 | public virtual void Foo() { }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/GlobalSuppressions.cs:
--------------------------------------------------------------------------------
1 | // This file is used by Code Analysis to maintain SuppressMessage
2 | // attributes that are applied to this project.
3 | // Project-level suppressions either have no target or are given
4 | // a specific target and scoped to a namespace, type, member, etc.
5 |
6 | using System.Diagnostics.CodeAnalysis;
7 |
8 | [assembly: SuppressMessage("Design", "CA1052:Static holder types should be Static or NotInheritable", Scope = "namespaceanddescendants", Target = "ReflectionHelpers.Cases")]
9 | [assembly: SuppressMessage("Microsoft.Performance", "CA1822", Scope = "namespaceanddescendants", Target = "ReflectionHelpers.Cases")]
10 | [assembly: SuppressMessage("Design", "CA1034:Nested types should not be visible", Scope = "namespaceanddescendants", Target = "ReflectionHelpers.Cases")]
11 | [assembly: SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Scope = "namespaceanddescendants", Target = "ReflectionHelpers.Cases")]
12 | [assembly: SuppressMessage("Globalization", "CA1307:Specify StringComparison")]
13 | [assembly: SuppressMessage("Design", "CA1062:Validate arguments of public methods")]
14 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/RazorCases/ComponentWithMethod.razor:
--------------------------------------------------------------------------------
1 | Foo
2 | @code {
3 | public void Foo() { }
4 | }
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/RazorCases/ComponentWithoutMethods.razor:
--------------------------------------------------------------------------------
1 | Foo
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/RazorCases/_Imports.razor:
--------------------------------------------------------------------------------
1 | @using Microsoft.AspNetCore.Components
2 | @using Microsoft.AspNetCore.Components.Web
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/SourceFileFinder.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5
5 | false
6 | ReflectionHelpers
7 | true
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | all
18 | runtime; build; native; contentfiles; analyzers; buildtransitive
19 |
20 |
21 | all
22 | runtime; build; native; contentfiles; analyzers; buildtransitive
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/SourceFileFinder.Tests/SourceFileFinderTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Diagnostics.CodeAnalysis;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Reflection;
6 | using ReflectionHelpers.Cases;
7 | using ReflectionHelpers.Cases.SubCases;
8 | using ReflectionHelpers.RazorCases;
9 | using Shouldly;
10 | using Xunit;
11 | using Xunit.Sdk;
12 | using static ReflectionHelpers.Cases.OuterClass;
13 | using static ReflectionHelpers.Cases.SubCases.OuterClass;
14 |
15 | namespace ReflectionHelpers
16 | {
17 | public class SourceFileFinderTest
18 | {
19 | private static readonly Assembly ThisAssembly = typeof(SourceFileFinderTest).Assembly;
20 |
21 | private static SourceFileFinder CreateSut(Assembly? assemblyToSearch = null)
22 | => new SourceFileFinder(assemblyToSearch ?? ThisAssembly);
23 |
24 | [Fact(DisplayName = "Find(type) returns false when source file does not exist on the local file system")]
25 | public void Test001()
26 | {
27 | var target = typeof(XunitTestCase);
28 | using var sut = CreateSut(target.Assembly);
29 |
30 | var result = sut.Find(typeof(XunitTestCase));
31 |
32 | result.ShouldBeEmpty();
33 | }
34 |
35 | [Fact(DisplayName = "Find(null) throws when method or type passed to it is null")]
36 | public void Test003()
37 | {
38 | using var sut = CreateSut();
39 |
40 | Should.Throw(() => sut.Find(null!).ToList())
41 | .ParamName.ShouldNotBeEmpty();
42 | }
43 |
44 | [Fact(DisplayName = "The search assembly is available through the SearchAssembly property")]
45 | public void Test004()
46 | {
47 | using var sut = CreateSut(ThisAssembly);
48 |
49 | sut.SearchAssembly.ShouldBe(ThisAssembly);
50 | }
51 |
52 | [Fact(DisplayName = "SourceFileFinder ctor throws when searchAssembly is missing")]
53 | public void Test005()
54 | {
55 | Should.Throw(() => new SourceFileFinder(null!))
56 | .ParamName.ShouldNotBeEmpty();
57 | }
58 |
59 | [Fact(DisplayName = "Find(type) throws when type passed to it does not belong to SerachAssembly")]
60 | public void Test006()
61 | {
62 | var target = typeof(XunitTestCase);
63 | using var sut = CreateSut();
64 |
65 | Should.Throw(() => sut.Find(target).ToList());
66 | }
67 |
68 | [Theory(DisplayName = "Find(type) can find source file for class")]
69 | [InlineData(typeof(EmptyClass))]
70 | [InlineData(typeof(ClassWithLineHidden))]
71 | [InlineData(typeof(EmptyClassInNestedNamespace))]
72 | [InlineData(typeof(NestedEmptyClass))]
73 | [InlineData(typeof(NestedEmptyClassInNestedNamespace))]
74 | [InlineData(typeof(ClassWithoutNamespace))]
75 | [InlineData(typeof(EmptyClassWithoutNamespace))]
76 | [InlineData(typeof(ClassWithCtor))]
77 | [InlineData(typeof(PublicMethodClass))]
78 | [InlineData(typeof(OverriddenPublicMethodClass))]
79 | [InlineData(typeof(ProtectedMethodClass))]
80 | [InlineData(typeof(OverriddenProtectedMethodClass))]
81 | [InlineData(typeof(PrivateMethodClass))]
82 | public void FindsFiles(Type target)
83 | {
84 | using var sut = CreateSut();
85 |
86 | var result = sut.Find(target);
87 |
88 | result.Single()
89 | .ShouldEndWith($@"SourceFileFinder.Tests{Path.DirectorySeparatorChar}Cases{Path.DirectorySeparatorChar}{target.Name}.cs");
90 | }
91 |
92 | [Theory(DisplayName = "Find(type) can find source file for generated razor component with one or more methods")]
93 | [InlineData(typeof(ComponentWithMethod))]
94 | public void FindsGeneratedRazorFilesWithMethods(Type target)
95 | {
96 | using var sut = CreateSut();
97 |
98 | var result = sut.Find(target).ToList();
99 |
100 | result.Count.ShouldBe(2);
101 | result.ShouldContain(file => file.EndsWith($@"SourceFileFinder.Tests{Path.DirectorySeparatorChar}RazorCases{Path.DirectorySeparatorChar}{target.Name}.razor"));
102 | result.ShouldContain(file => file.EndsWith($@"{Path.DirectorySeparatorChar}RazorCases{Path.DirectorySeparatorChar}{target.Name}.razor.g.cs"));
103 | }
104 |
105 | [Theory(DisplayName = "Find(type) can find source file for generated razor component without methods")]
106 | [InlineData(typeof(ComponentWithoutMethods))]
107 | public void FindsGeneratedRazorFilesWithoutMethods(Type target)
108 | {
109 | using var sut = CreateSut();
110 |
111 | var result = sut.Find(target);
112 |
113 | result.ShouldHaveSingleItem().ShouldEndWith($@"{Path.DirectorySeparatorChar}RazorCases{Path.DirectorySeparatorChar}{target.Name}.razor.g.cs");
114 | }
115 |
116 |
117 | [Fact(DisplayName = "Find(type), where type is partial with a method in each partial class, " +
118 | " returns all source files")]
119 | public void Test110()
120 | {
121 | var target = typeof(PartialClassWithMethod);
122 | using var sut = CreateSut();
123 |
124 | var result = sut.Find(target).ToList();
125 |
126 | result.ShouldContain(file => file.EndsWith(@$"SourceFileFinder.Tests{Path.DirectorySeparatorChar}Cases{Path.DirectorySeparatorChar}{target.Name}.1.cs"));
127 | result.ShouldContain(file => file.EndsWith(@$"SourceFileFinder.Tests{Path.DirectorySeparatorChar}Cases{Path.DirectorySeparatorChar}{target.Name}.2.cs"));
128 | }
129 |
130 | // Tests TODO:
131 | // - Create test of classes with sequence points in documents (you can make one. just switch #line's back and forth a few times or just use #line hidden in the middle and then restore to non hidden)
132 | // it may be required that you add #line somefakeline "somefakefile" too. I believe hidden lines create sequence points but this is still a single document
133 | // "somefakefile" should be a full path.
134 | // - No portable PDB file was found for assembly
135 | // - Partial class without method in one or more files
136 | // - Multiple classes in same file
137 | // - Create test with assembly compiled using full and pdb-only format. Most likely need a windows pdb reader (https://github.com/dotnet/symreader)
138 |
139 | // none = no debug data
140 | // pdbonly = Windows PDB format in a .pdb file
141 | // full = Windows PDB format embedded in the .dll file (this is in the legacy csproj default template, I think)
142 | // portable = IL PDB format in a .pdb file (this is the .NET SDK default)
143 | // embedded = IL PDB format embedded in the .dll file
144 | }
145 | }
146 |
--------------------------------------------------------------------------------
/SourceFileFinder.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30011.22
5 | MinimumVisualStudioVersion = 15.0.26124.0
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SourceFileFinder", "SourceFileFinder\SourceFileFinder.csproj", "{49A39CB8-E857-45B5-A9C8-AE34C0724BF4}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SourceFileFinder.Tests", "SourceFileFinder.Tests\SourceFileFinder.Tests.csproj", "{82928125-ED46-41E5-A4EF-AE02C817E862}"
9 | EndProject
10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{048283D8-8D21-4EB6-9464-B2AF1F9AABC2}"
11 | ProjectSection(SolutionItems) = preProject
12 | Directory.Build.props = Directory.Build.props
13 | README.md = README.md
14 | EndProjectSection
15 | EndProject
16 | Global
17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
18 | Debug|Any CPU = Debug|Any CPU
19 | Debug|x64 = Debug|x64
20 | Debug|x86 = Debug|x86
21 | Release|Any CPU = Release|Any CPU
22 | Release|x64 = Release|x64
23 | Release|x86 = Release|x86
24 | EndGlobalSection
25 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
26 | {49A39CB8-E857-45B5-A9C8-AE34C0724BF4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {49A39CB8-E857-45B5-A9C8-AE34C0724BF4}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {49A39CB8-E857-45B5-A9C8-AE34C0724BF4}.Debug|x64.ActiveCfg = Debug|Any CPU
29 | {49A39CB8-E857-45B5-A9C8-AE34C0724BF4}.Debug|x64.Build.0 = Debug|Any CPU
30 | {49A39CB8-E857-45B5-A9C8-AE34C0724BF4}.Debug|x86.ActiveCfg = Debug|Any CPU
31 | {49A39CB8-E857-45B5-A9C8-AE34C0724BF4}.Debug|x86.Build.0 = Debug|Any CPU
32 | {49A39CB8-E857-45B5-A9C8-AE34C0724BF4}.Release|Any CPU.ActiveCfg = Release|Any CPU
33 | {49A39CB8-E857-45B5-A9C8-AE34C0724BF4}.Release|Any CPU.Build.0 = Release|Any CPU
34 | {49A39CB8-E857-45B5-A9C8-AE34C0724BF4}.Release|x64.ActiveCfg = Release|Any CPU
35 | {49A39CB8-E857-45B5-A9C8-AE34C0724BF4}.Release|x64.Build.0 = Release|Any CPU
36 | {49A39CB8-E857-45B5-A9C8-AE34C0724BF4}.Release|x86.ActiveCfg = Release|Any CPU
37 | {49A39CB8-E857-45B5-A9C8-AE34C0724BF4}.Release|x86.Build.0 = Release|Any CPU
38 | {82928125-ED46-41E5-A4EF-AE02C817E862}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
39 | {82928125-ED46-41E5-A4EF-AE02C817E862}.Debug|Any CPU.Build.0 = Debug|Any CPU
40 | {82928125-ED46-41E5-A4EF-AE02C817E862}.Debug|x64.ActiveCfg = Debug|Any CPU
41 | {82928125-ED46-41E5-A4EF-AE02C817E862}.Debug|x64.Build.0 = Debug|Any CPU
42 | {82928125-ED46-41E5-A4EF-AE02C817E862}.Debug|x86.ActiveCfg = Debug|Any CPU
43 | {82928125-ED46-41E5-A4EF-AE02C817E862}.Debug|x86.Build.0 = Debug|Any CPU
44 | {82928125-ED46-41E5-A4EF-AE02C817E862}.Release|Any CPU.ActiveCfg = Release|Any CPU
45 | {82928125-ED46-41E5-A4EF-AE02C817E862}.Release|Any CPU.Build.0 = Release|Any CPU
46 | {82928125-ED46-41E5-A4EF-AE02C817E862}.Release|x64.ActiveCfg = Release|Any CPU
47 | {82928125-ED46-41E5-A4EF-AE02C817E862}.Release|x64.Build.0 = Release|Any CPU
48 | {82928125-ED46-41E5-A4EF-AE02C817E862}.Release|x86.ActiveCfg = Release|Any CPU
49 | {82928125-ED46-41E5-A4EF-AE02C817E862}.Release|x86.Build.0 = Release|Any CPU
50 | EndGlobalSection
51 | GlobalSection(SolutionProperties) = preSolution
52 | HideSolutionNode = FALSE
53 | EndGlobalSection
54 | GlobalSection(ExtensibilityGlobals) = postSolution
55 | SolutionGuid = {B6FD4982-E0DB-420C-832A-230B7B87FDA9}
56 | EndGlobalSection
57 | EndGlobal
58 |
--------------------------------------------------------------------------------
/SourceFileFinder/CSharpTypeLocator.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Collections.Generic;
6 | using Microsoft.CodeAnalysis.CSharp;
7 | using Microsoft.CodeAnalysis;
8 | using Microsoft.CodeAnalysis.CSharp.Syntax;
9 |
10 | namespace ReflectionHelpers
11 | {
12 | internal class CSharpTypeLocator
13 | {
14 | private readonly Dictionary _syntaxTreeCache = new Dictionary();
15 |
16 | public bool CsharpDocumentContainsType(string filename, Type target)
17 | {
18 | if (!File.Exists(filename))
19 | return false;
20 |
21 | var root = GetCombilationRoot(filename);
22 |
23 | var classDeclarations = root.DescendantNodesAndSelf(descendIntoTrivia: false)
24 | .Where(x => x.IsKind(SyntaxKind.ClassDeclaration))
25 | .OfType()
26 | .Where(x => x.Identifier.Text.Equals(target.Name, StringComparison.Ordinal))
27 | .ToList();
28 |
29 | if (target.Namespace is null)
30 | return classDeclarations.Any();
31 | else
32 | return classDeclarations.Any(classDeclaration =>
33 | {
34 | var fullname = GetFullName(classDeclaration);
35 | return fullname.Equals(target.FullName, StringComparison.Ordinal);
36 | });
37 | }
38 |
39 | private CompilationUnitSyntax GetCombilationRoot(string filename)
40 | {
41 | if (_syntaxTreeCache.TryGetValue(filename, out var result))
42 | return result;
43 | else
44 | {
45 | var programText = File.ReadAllText(filename);
46 | var tree = CSharpSyntaxTree.ParseText(programText);
47 | var root = tree.GetCompilationUnitRoot();
48 | _syntaxTreeCache.Add(filename, root);
49 | return root;
50 | }
51 | }
52 |
53 | private static string GetFullName(ClassDeclarationSyntax source)
54 | {
55 | const string NESTED_CLASS_DELIMITER = "+";
56 | const string NAMESPACE_CLASS_DELIMITER = ".";
57 |
58 | if (source is null)
59 | throw new ArgumentNullException(nameof(source));
60 |
61 | //var items = new List();
62 | var result = new StringBuilder();
63 | result.Append(source.Identifier.ValueText);
64 |
65 | var parent = source.Parent;
66 |
67 | while (parent.IsKind(SyntaxKind.ClassDeclaration))
68 | {
69 | if (parent is ClassDeclarationSyntax parentClass)
70 | {
71 | result.Insert(0, NESTED_CLASS_DELIMITER);
72 | result.Insert(0, parentClass.Identifier.ValueText);
73 | }
74 | parent = parent.Parent;
75 | }
76 |
77 | while (parent.IsKind(SyntaxKind.NamespaceDeclaration))
78 | {
79 | if (parent is NamespaceDeclarationSyntax namespaceDeclaration)
80 | {
81 | result.Insert(0, NAMESPACE_CLASS_DELIMITER);
82 | result.Insert(0, namespaceDeclaration.Name.ToString());
83 | }
84 | parent = parent.Parent;
85 | }
86 |
87 | return result.ToString();
88 | }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/SourceFileFinder/GlobalSuppressions.cs:
--------------------------------------------------------------------------------
1 | // This file is used by Code Analysis to maintain SuppressMessage
2 | // attributes that are applied to this project.
3 | // Project-level suppressions either have no target or are given
4 | // a specific target and scoped to a namespace, type, member, etc.
5 |
6 | using System.Diagnostics.CodeAnalysis;
7 |
8 | [assembly: SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters")]
9 | [assembly: SuppressMessage("Design", "CA1063:Implement IDisposable Correctly")]
10 | [assembly: SuppressMessage("Usage", "CA1816:Dispose methods should call SuppressFinalize")]
11 |
--------------------------------------------------------------------------------
/SourceFileFinder/MemberInfoExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Reflection;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace ReflectionHelpers
9 | {
10 | ///
11 | /// Extensions for .
12 | /// Copied from https://source.dot.net/#System.Reflection.TypeExtensions/System/Reflection/TypeExtensions.cs,277.
13 | ///
14 | public static class MemberInfoExtensions
15 | {
16 |
17 | ///
18 | /// Determines if there is a metadata token available for the given member.
19 | /// throws otherwise.
20 | ///
21 | /// This maybe
22 | public static bool HasMetadataToken(this MemberInfo member)
23 | {
24 | if (member is null)
25 | throw new ArgumentNullException(nameof(member));
26 | try
27 | {
28 | return GetMetadataTokenOrZeroOrThrow(member) != 0;
29 | }
30 | catch (InvalidOperationException)
31 | {
32 | // Thrown for unbaked ref-emit members/types.
33 | // Other cases such as typeof(byte[]).MetadataToken will be handled by comparison to zero above.
34 | return false;
35 | }
36 | }
37 |
38 | ///
39 | /// Gets a metadata token for the given member if available. The returned token is never nil.
40 | ///
41 | ///
42 | /// There is no metadata token available. returns false in this case.
43 | ///
44 | public static int GetMetadataToken(this MemberInfo member)
45 | {
46 | if (member is null)
47 | throw new ArgumentNullException(nameof(member));
48 | int token = GetMetadataTokenOrZeroOrThrow(member);
49 |
50 | if (token == 0)
51 | {
52 | throw new InvalidOperationException("There is no metadata token available for the given member.");
53 | }
54 |
55 | return token;
56 | }
57 |
58 | private static int GetMetadataTokenOrZeroOrThrow(MemberInfo member)
59 | {
60 | int token = member.MetadataToken;
61 |
62 | // Tokens have MSB = table index, 3 LSBs = row index
63 | // row index of 0 is a nil token
64 | const int rowMask = 0x00FFFFFF;
65 | if ((token & rowMask) == 0)
66 | {
67 | // Nil token is returned for edge cases like typeof(byte[]).MetadataToken.
68 | return 0;
69 | }
70 |
71 | return token;
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/SourceFileFinder/SourceFileFinder.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Reflection;
4 | using System.Reflection.Metadata;
5 | using System.Reflection.Metadata.Ecma335;
6 | using System.Reflection.PortableExecutable;
7 | using System.Collections.Generic;
8 | using System.Diagnostics.CodeAnalysis;
9 |
10 | namespace ReflectionHelpers
11 | {
12 |
13 | ///
14 | /// Represents a helper utility that can find a source file for
15 | /// a type or method that is a part of a compiled assembly.
16 | ///
17 | public class SourceFileFinder : IDisposable
18 | {
19 | private static readonly Guid CSharpLanguage = Guid.Parse("3f5162f8-07c6-11d3-9053-00c04fa302a1");
20 | private static readonly Guid FSharpLanguage = Guid.Parse("ab4f38c9-b6e6-43ba-be3b-58080b2ccce3");
21 | private static readonly Guid VBLanguage = Guid.Parse("3a12d0b8-c26c-11d0-b442-00a0244a1dd2");
22 |
23 | private readonly CSharpTypeLocator _csharpTypeLocator = new();
24 |
25 | private FileStream? _dllFileReader;
26 | private FileStream? _pdbFileReader;
27 | private PEReader? _pEReader;
28 | private MetadataReaderProvider? _metadataReaderProvider;
29 | private MetadataReader? _metadataReader;
30 | private MetadataReader? _pdbReader;
31 |
32 | ///
33 | /// Gets the MetadataReader for the .
34 | ///
35 | protected MetadataReader MetadataReader
36 | {
37 | get
38 | {
39 | if (_metadataReader is null)
40 | Initialize();
41 |
42 | return _metadataReader!; // BANG! because Initialized() should set _metadateReader.
43 | }
44 | }
45 |
46 | ///
47 | /// Gets the MetadataReader for the PDB for the .
48 | ///
49 | protected MetadataReader PdbReader
50 | {
51 | get
52 | {
53 | if (_pdbReader is null)
54 | Initialize();
55 |
56 | return _pdbReader!; // BANG! because Initialized() should set _pdbReader.
57 | }
58 | }
59 |
60 | ///
61 | /// Gets the assembly being used when trying to find source files.
62 | ///
63 | public Assembly SearchAssembly { get; }
64 |
65 | ///
66 | /// Creates an instance of the .
67 | ///
68 | /// The assembly to use when searching for the source file.
69 | public SourceFileFinder(Assembly searchAssembly)
70 | {
71 | SearchAssembly = searchAssembly ?? throw new ArgumentNullException(nameof(searchAssembly));
72 | }
73 |
74 | ///
75 | /// Will attempt to find the local source file(s) where the is declared.
76 | ///
77 | /// Type whose source to attempt to find.
78 | /// A list of files the type is defined in.
79 | public IEnumerable Find(Type target)
80 | {
81 | if (target is null)
82 | throw new ArgumentNullException(nameof(target));
83 | if (target.Assembly != SearchAssembly)
84 | throw new InvalidOperationException($"The type '{target.FullName}' does not belong to finder's search assembly '{SearchAssembly.FullName}'.");
85 |
86 | var typeDefinition = GetTypeDefinition(target);
87 |
88 | var fileTracker = new HashSet();
89 |
90 | foreach (var file in FindFilesViaMethods(typeDefinition, fileTracker))
91 | {
92 | yield return file;
93 | }
94 | foreach (var file in FindFilesViaDocuments(target, fileTracker))
95 | {
96 | yield return file;
97 | }
98 | }
99 |
100 | private TypeDefinition GetTypeDefinition(Type target)
101 | {
102 | var typeDefinitionHandle = (TypeDefinitionHandle)MetadataTokens.Handle(target.GetMetadataToken());
103 | return MetadataReader.GetTypeDefinition(typeDefinitionHandle);
104 | }
105 |
106 | private IEnumerable FindFilesViaMethods(TypeDefinition typeDefinition, HashSet fileTracker)
107 | {
108 | foreach (var handle in typeDefinition.GetMethods())
109 | {
110 | if (handle.IsNil)
111 | continue;
112 |
113 | var methodDebugInformation = PdbReader.GetMethodDebugInformation(handle);
114 | if (methodDebugInformation.Document.IsNil)
115 | continue;
116 |
117 | var doc = PdbReader.GetDocument(methodDebugInformation.Document);
118 | if (doc.Name.IsNil)
119 | continue;
120 |
121 | var filename = PdbReader.GetString(doc.Name);
122 |
123 | if (fileTracker.Contains(filename))
124 | continue;
125 | else
126 | fileTracker.Add(filename);
127 |
128 | if (!File.Exists(filename))
129 | continue;
130 |
131 | yield return filename;
132 | }
133 | }
134 |
135 | private IEnumerable FindFilesViaDocuments(Type target, HashSet fileTracker)
136 | {
137 | foreach (var handle in PdbReader.Documents)
138 | {
139 | if (handle.IsNil)
140 | continue;
141 |
142 | var doc = PdbReader.GetDocument(handle);
143 |
144 | if (doc.Name.IsNil)
145 | continue;
146 |
147 | if (doc.Language.IsNil)
148 | continue;
149 |
150 | var language = PdbReader.GetGuid(doc.Language);
151 | var filename = PdbReader.GetString(doc.Name);
152 |
153 | if (fileTracker.Contains(filename))
154 | continue;
155 | else
156 | fileTracker.Add(filename);
157 |
158 | if (language == CSharpLanguage && _csharpTypeLocator.CsharpDocumentContainsType(filename, target))
159 | {
160 | yield return filename;
161 | continue;
162 | }
163 |
164 | if (language == VBLanguage)
165 | throw new NotImplementedException("Support for Visual Basic not implemented yet.");
166 | if (language == FSharpLanguage)
167 | throw new NotImplementedException("Support for F# not implemented yet.");
168 | }
169 | }
170 |
171 | private void Initialize()
172 | {
173 | if (_dllFileReader is null)
174 | _dllFileReader = File.OpenRead(SearchAssembly.Location);
175 |
176 | if (_pEReader is null)
177 | _pEReader = new PEReader(_dllFileReader);
178 |
179 | if (_metadataReader is null && _pdbReader is null)
180 | {
181 | bool pdbFound = false;
182 | try
183 | {
184 | pdbFound = _pEReader.TryOpenAssociatedPortablePdb(SearchAssembly.Location,
185 | pdbPath =>
186 | {
187 | _pdbFileReader = File.OpenRead(pdbPath);
188 | return _pdbFileReader;
189 | },
190 | out var metadataReaderProvider,
191 | out var pdbPath);
192 |
193 |
194 | _metadataReaderProvider = metadataReaderProvider;
195 | }
196 | catch (Exception ex)
197 | {
198 | throw new InvalidOperationException($"An error occurred while searching for the PDB for the assembly '{SearchAssembly.FullName}' with path '{SearchAssembly.Location}'.", ex);
199 | }
200 |
201 | if (!pdbFound)
202 | throw new InvalidOperationException($"No portable PDB was found for the assembly '{SearchAssembly.FullName}' with path '{SearchAssembly.Location}'.");
203 |
204 | _metadataReader = _pEReader.GetMetadataReader();
205 | _pdbReader = _metadataReaderProvider?.GetMetadataReader();
206 | }
207 | }
208 |
209 |
210 | ///
211 | public void Dispose()
212 | {
213 | if (_pEReader is { })
214 | {
215 | _pEReader.Dispose();
216 | _pEReader = null;
217 | }
218 |
219 | if (_metadataReaderProvider is { })
220 | {
221 | _metadataReaderProvider.Dispose();
222 | _metadataReaderProvider = null;
223 | }
224 |
225 | try
226 | {
227 | // Remarks in docs says to dispose in a try/catch block:
228 | // https://docs.microsoft.com/en-us/dotnet/api/system.io.filestream?view=netcore-3.1#remarks
229 | if (_dllFileReader is { })
230 | {
231 | _dllFileReader.Dispose();
232 | _dllFileReader = null;
233 | }
234 |
235 | if (_pdbFileReader is { })
236 | {
237 | _pdbFileReader.Dispose();
238 | _pdbFileReader = null;
239 | }
240 | }
241 | catch
242 | { }
243 | }
244 | }
245 | }
246 |
--------------------------------------------------------------------------------
/SourceFileFinder/SourceFileFinder.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.1
5 | ReflectionHelpers
6 | true
7 | SourceFileFinder
8 | SourceFileFinder
9 | A small helper library, that allows you to find the source file of a type at runtime, based on the debug information included in the types assembly through the related portable PDB.
10 | MIT
11 | https://github.com/egil/SourceFileFinder
12 | https://github.com/egil/SourceFileFinder.git
13 | git
14 | c# reflection
15 | Egil Hansen
16 | Egil Hansen
17 | true
18 | true
19 | true
20 | embedded
21 | snupkg
22 | true
23 | latest
24 | true
25 | true
26 | ../key.snk
27 |
28 |
29 |
30 | true
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/SourceFileFinder/build.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | true
5 | embedded
6 |
7 |
--------------------------------------------------------------------------------
/SourceFileFinder/buildMultiTargeting.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "rollForward": "latestMajor",
4 | "allowPrerelease": false
5 | }
6 | }
--------------------------------------------------------------------------------
/key.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/egil/SourceFileFinder/7aad853ad358c8a120a0251c2dd36cd6bee77f37/key.snk
--------------------------------------------------------------------------------
/version.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json",
3 | "version": "1.1.0",
4 | "publicReleaseRefSpec": [
5 | "^refs/heads/master$",
6 | "^refs/heads/v\\d+(?:\\.\\d+)?$"
7 | ],
8 | "cloudBuild": {
9 | "setVersionVariables": true,
10 | "buildNumber": {
11 | "enabled": true
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------