Repository: dotMorten/DotNetOMDGenerator Branch: main Commit: e3394341081a Files: 24 Total size: 269.9 KB Directory structure: gitextract_07wspkb4/ ├── .gitignore ├── LICENSE ├── README.md ├── TestCode/ │ ├── NewCode/ │ │ ├── Class1.cs │ │ ├── Enum1.cs │ │ ├── Interface1.cs │ │ └── NmeaParser.xml │ └── OldCode/ │ ├── Class1.cs │ ├── Enum1.cs │ ├── Interface1.cs │ └── NmeaParser.xml └── src/ ├── Generator/ │ ├── ArgumentParser.cs │ ├── Generator.csproj │ ├── Generators/ │ │ ├── HtmlOmdFooter.html │ │ ├── HtmlOmdGenerator.cs │ │ ├── HtmlOmdHeader.html │ │ ├── MarkdownGenerator.cs │ │ └── OMDGenerator.cs │ ├── ICodeGenerator.cs │ ├── Program.cs │ ├── TypeExtensions.cs │ ├── WorkspaceHelper.cs │ └── dotMorten.OmdGenerator.targets └── Generator.sln ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # User-specific files *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ # Visual Studio 2015 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUNIT *.VisualState.xml TestResult.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # .NET Core project.lock.json project.fragment.lock.json artifacts/ **/Properties/launchSettings.json *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # JustCode is a .NET coding add-in .JustCode # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # Visual Studio code coverage results *.coverage *.coveragexml # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # TODO: Comment the next line if you want to checkin your web deploy settings # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/packages/* # except build/, which is used as an MSBuild target. !**/packages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/packages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings orleans.codegen.cs # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm # SQL Server files *.mdf *.ldf *.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat node_modules/ # Typescript v1 declaration files typings/ # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # JetBrains Rider .idea/ *.sln.iml # CodeRush .cr/ # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc # Cake - Uncomment if you are using it # tools/** # !tools/packages.config # Telerik's JustMock configuration file *.jmconfig # BizTalk build output *.btp.cs *.btm.cs *.odx.cs *.xsd.cs src/BuildTask/nuget/ ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # .NET Object Model Diagram Generator A cross-platform Roslyn-based tool that generates an object model diagram of a set of C# source files and/or .NET assemblies ## Sponsoring If you like this library and use it a lot, consider sponsoring me. Anything helps and encourages me to keep going. See here for details: https://github.com/sponsors/dotMorten ### Install Run the following command from commandline (requires .NET Core 2.1 installed): ``` dotnet tool install --global dotMorten.OmdGenerator ``` ### Usage: ``` generateomd /source=[source folder] /compareSource=[oldSourceFolder] /preprocessors=[defines] /format=[html|image] /showPrivate /showInternal Required parameters: source Specifies the folder of source files to include for the object model. Separate with ; for multiple folders or assemblies Specifies a set of assemblies to include for the object model. Separate with ; for multiple assemblies, or use wildcards Optional parameters: compareSource Specifies a folder of old source to compare and generate a diff model This can be useful for finding API changes or compare branches compareAssemblies Specifies a set of old assemblies to compare and generate a adiff model. Separate with; for multiple assemblies, or use wildcards format Format to generate: 'html' a single html output (html is default) 'md' for markdown you can copy-paste to for instance GitHub. Specify multiple with a semicolon seperator, and use an output filename without extension preprocessors Define a set of preprocessors values. Use ; to separate multiple exclude Defines one or more strings that can't be part of the path Ie '*/Samples/*;*/UnitTests/*' (use forward slash for folder separators) regexfilter Defines a regular expression for filtering on full file names in the source showPrivate Show private members (default is false) showInternal Show internal members (default is false) output Filename to write the output to (extension is optional, but exclude the extension if you specify multiple formats) ``` ### NuGet As an alternative you can also reference a [NuGet package](https://www.nuget.org/packages/dotMorten.OmdGenerator/) to your class library, and set up a post-build script to generate an Object Model Diagram HTML file: ``` Install-Package dotMorten.OmdGenerator ``` Add the following to your project: ```xml ``` An example of a generated output for all of .NET Core can be found [here](http://www.sharpgis.net/Tests/corefx.html). It can also be used to compare two folders (for instance two separate branches) and only show changes to the API. [Here's an example of .NET CoreFX v2.0 vs Master](http://www.sharpgis.net/Tests/corefx_new.html). [![Screenshot](Screenshot.png)](http://www.sharpgis.net/Tests/corefx.html) ### Examples Generate OMD for .NET Core FX source code, and ignore ref and test folders: ``` generateomd /source=c:\github\dotnet\corefx\src /exclude="*/ref/*;*/tests/*;*/perftests/*" ``` Compare .NET CoreFX Master with v2.0.0 repo branches directly from their Github zipped downloads: ``` generateomd /source=https://github.com/dotnet/corefx/archive/master.zip /compareSource=https://github.com/dotnet/corefx/archive/release/2.0.0.zip /exclude="*/ref/*;*/tests/*;*/perftests/*" ``` What's new in Xamarin.Forms? Compare assemblies from the nuget cache: ``` generateomd /assemblies=%USERPROFILE%\.nuget\packages\xamarin.forms\3.3.0.912540\lib\netstandard2.0\*.dll /compareAsssemblies=%USERPROFILE%\.nuget\packages\xamarin.forms\3.2.0.871581\lib\netstandard2.0\*.dll ``` ================================================ FILE: TestCode/NewCode/Class1.cs ================================================ using System; using System.Threading.Tasks; public namespace RootNamespace { public class BaseClass { public abstract void SomeBaseMethod(); public void AVoidMethod() { } } public class MyClass : BaseClass, IDisposable { MyClass() { } [Obsolete] MyClass(int obseleteOverload) { } public Task ATaskReturningGenericMethod() { } public double ProtectedSetProperty { get; protected set; } public double WritableProperty { get; set; } public double ReadOnlyProperty { get; } public double SetOnlyProperty { set; } [Obsolete] public void AlreadyObsoletedMethod(); [Obsolete] public void ObsoletedMethod(); [Obsolete] public double ObsoletedProperty { set; } public event EventHandler SimpleEvent; public event EventHandler GenericEvent; [Obsolete] public event EventHandler ObsoletedEvent { set; } public void Dispose() { } public override void SomeBaseMethod() {} } [Obsolete] public class ObsoletedClass {} } ================================================ FILE: TestCode/NewCode/Enum1.cs ================================================ using System; public namespace RootNamespace { public enum ShortEnum : short { Zero=0, One=1, Two=2 } public enum SimpleEnum { Unknown=-1, One=1, /*Two=2,*/ Three = 3 } [Flags] public enum FlagsEnum { Zero = 0, One = 1, Two = 2, Four = 4, [Obsolete] Obsolete = 5, All = 255, } } ================================================ FILE: TestCode/NewCode/Interface1.cs ================================================ using System; using System.Threading.Tasks; public namespace RootNamespace { public interface Interface1 { void Method(); } public interface DerivedInterface : Interface1 { void Method2(); } } ================================================ FILE: TestCode/NewCode/NmeaParser.xml ================================================ NmeaParser An abstract generic NMEA device that reads a stream at a decreased pace, mostly used to emulate NMEA input from files and strings. Initializes a new instance of the class. Initializes a new instance of the class. The time to wait between each group of lines being read in milliseconds Gets the stream to perform buffer reads on. Opens the stream asynchronous. Closes the stream asynchronous. The stream. Initializes a new instance of the class. The stream. The read speed in milliseconds. Gets a value indicating whether this instance can read. true if this instance can read; otherwise, false. Gets a value indicating whether this instance can seek. true if this instance can seek; otherwise, false. Gets a value indicating whether this instance can write. true if this instance can write; otherwise, false. Flushes this instance. Gets the length. The length. Gets or sets the position. The position. Reads the specified buffer. The buffer. The offset. The count. Seeks the specified offset. The offset. The origin. Sets the length. The value. Writes the specified buffer to the device. The buffer. The offset. The count. Releases unmanaged and - optionally - managed resources. true to release both managed and unmanaged resources; false to release only unmanaged resources. Total number of messages of this type in this cycle Message number A generic abstract NMEA device Initializes a new instance of the class. Opens the device connection. Creates the stream the NmeaDevice is working on top off. Closes the device. Closes the stream the NmeaDevice is working on top off. The stream. Occurs when an NMEA message is received. Releases unmanaged and - optionally - managed resources. Releases unmanaged and - optionally - managed resources. true to release both managed and unmanaged resources; false to release only unmanaged resources. Gets a value indicating whether this device is open. true if this instance is open; otherwise, false. Event argument for the Gets the nmea message. The nmea message. Gets a value indicating whether this instance is a multi part message. true if this instance is multi part; otherwise, false. Gets the message parts if this is a multi-part message and all message parts has been received. The message parts. A file-based NMEA device reading from a NMEA log file. Initializes a new instance of the class. Initializes a new instance of the class. The time to wait between each group of lines being read in milliseconds Gets the name of the nmea file this device is using. Gets the stream to perform buffer reads on. GALILEO Satellites in view Global Positioning System Fix Data Called when the message is being loaded. The NMEA message values. Time of day fix was taken Latitude Longitude Fix Quality Number of satellites being tracked Horizontal Dilution of Precision Altitude Altitude units ('M' for Meters) Height of geoid (mean sea level) above WGS84 Altitude units ('M' for Meters) Time since last DGPS update DGPS Station ID Number Geographic position, latitude / longitude Called when the message is being loaded. The NMEA message values. Latitude Longitude Time since last DGPS update Gets a value indicating whether data is active. true if data is active; otherwise, false. Fix data for GLONASS satellite navigation systems GLONASS Satellites in view Fixes data for single or combined (GPS, GLONASS, possible future satellite systems, and systems combining these) satellite navigation systems GNS Mode Indicator No fix. Satellite system not used in position fix, or fix not valid Autonomous. Satellite system used in non-differential mode in position fix Differential (including all OmniSTAR services). Satellite system used in differential mode in position fix Precise. Satellite system used in precision mode. Precision mode is defined as no deliberate degradation (such as Selective Availability) and higher resolution code (P-code) is used to compute position fix. Real Time Kinematic. Satellite system used in RTK mode with fixed integers Float RTK. Satellite system used in real time kinematic mode with floating integers Estimated (dead reckoning) mode Manual input mode Simulator mode Navigational status Not valid for navigation Safe Caution Unsafe Called when the message is being loaded. The NMEA message values. Time of day fix was taken Latitude Longitude Mode indicator for GPS Mode indicator for GLONASS Mode indicator for future constallations Number of satellites (SVs) in use Horizontal Dilution of Precision (HDOP), calculated using all the satellites (GPS, GLONASS, and any future satellites) used in computing the solution reported in each GNS sentence. Orthometric height in meters (MSL reference) Geoidal separation in meters - the difference between the earth ellipsoid surface and mean-sea-level (geoid) surface defined by the reference datum used in the position solution
'-' = mean-sea-level surface below ellipsoid.
Age of differential data - if talker ID is GN, additional GNS messages follow with GP and/or GL Age of differential data eference station ID1, range 0000-4095 - Null if talker ID is GN, additional GNS messages follow with GP and/or GL Reference station ID Navigational status Global Positioning System Fix Data Geographic position, latitude / longitude Global Positioning System Fix Data Position error statistics Recommended Minimum Fixes data for single or combined (GPS, GLONASS, possible future satellite systems, and systems combining these) satellite navigation systems Recommended Minimum Called when the message is being loaded. The NMEA message values. Estimated horizontal position error in meters (HPE) Range: 0.0 to 999.9 meters Horizontal Error unit ('M' for Meters) Estimated vertical position error in meters (VPE) Range: 0.0 to 999.9 meters Vertical Error unit ('M' for Meters) Overall spherical equivalent position error (EPE) Range: 0.0 to 999.9 meters Spherical Error unit ('M' for Meters) Altitude Information Altitude unit Unknown Feet Position Fix Dimension Unknown No fix 2D Fix 3D Fix Called when the message is being loaded. The NMEA message values. Current altitude Horizontal Error unit ('f' for Meters) Fix type Bearing Origin to Destination Called when the message is being loaded. The NMEA message values. True Bearing from start to destination Magnetic Bearing from start to destination Name of origin Name of destination Global Positioning System Fix Data Fix quality Invalid GPS Differential GPS Precise Positioning Service Real Time Kinematic (Fixed) Real Time Kinematic (Floating) Estimated Manual input Simulation Geographic position, latitude / longitude Fixes data for GPS satellite navigation systems Global Positioning System Fix Data Mode selection Auto Manual mode Fix Mode Not available 2D Fix 3D Fix Position error statistics GLONASS Satellites in view Satellite vehicle SV PRN number Elevation in degrees, 90 maximum Azimuth, degrees from true north, 000 to 359 Signal-to-Noise ratio, 0-99 dB (-1 when not tracking) Satellite system Satellite system Unknown GPS - Global Positioning System (NAVSTAR) WAAS - Wide Area Augmentation System GLONASS - Globalnaya navigatsionnaya sputnikovaya sistema Galileo Recommended minimum navigation information Data status Ok Warning Called when the message is being loaded. The NMEA message values. Data Status Cross-track error (steer left when negative, right when positive) Origin waypoint ID Destination waypoint ID Destination Latitude Destination Longitude Range to destination in nautical miles True bearing to destination Velocity towards destination in knots Arrived (true if arrived) Recommended Minimum Routes Waypoint tpe Complete list of waypoints List of remaining waypoints Called when the message is being loaded. The NMEA message values. Total number of messages of this type in this cycle Message number Gets the type of the list. Gets the route identifier. Waypoints Returns an enumerator that iterates through the collection. A System.Collections.Generic.IEnumerator{T} that can be used to iterate through the collection. Returns an enumerator that iterates through a collection. An System.Collections.IEnumerator object that can be used to iterate through the collection. Global Positioning System Fix Data Called when the message is being loaded. The NMEA message values. Mode Mode IDs of SVs used in position fix Dilution of precision Horizontal dilution of precision Vertical dilution of precision Position error statistics Called when the message is being loaded. The NMEA message values. UTC of position fix RMS value of the pseudorange residuals; includes carrier phase residuals during periods of RTK (float) and RTK (fixed) processing Error ellipse semi-major axis 1 sigma error, in meters Error ellipse semi-minor axis 1 sigma error, in meters Error ellipse orientation, degrees from true north Latitude 1 sigma error, in meters The error expressed as one standard deviation. Longitude 1 sigma error, in meters The error expressed as one standard deviation. Height 1 sigma error, in meters The error expressed as one standard deviation. GPS Satellites in view Called when the message is being loaded. The NMEA message values. Total number of messages of this type in this cycle Message number Total number of SVs in view Dilution of precision Returns an enumerator that iterates through the collection. A System.Collections.Generic.IEnumerator{SatelliteVehicle} that can be used to iterate through the collection. Returns an enumerator that iterates through a collection. An System.Collections.IEnumerator object that can be used to iterate through the collection. Laser Range Measurement Called when the message is being loaded. The NMEA message values. Gets the horizontal vector. Gets the horizontal distance. Gets the units of the value. Gets the horizontal angle. Gets the units of the value. Gets the vertical angle. Gets the units of the value. Gets the slope distance. Gets the units of the value. Laser Range Burden finder Tree Measurement Called when the message is being loaded. The NMEA message values. Gets the height of the tree. Gets the message height of the tree. Gets the units of the value. Gets the tree diameter. Gets the measured tree diameter. Gets the units of the value. Nmea message attribute type used on concrete implementations. Initializes a new instance of the class. The type. Gets or sets the NMEA message type. NMEA Message base class. Parses the specified NMEA message. The NMEA message string. Invalid nmea message: Missing starting character '$' or checksum failure Gets the NMEA message parts. Gets the NMEA type id for the message. Called when the message is being loaded. The NMEA message values. Implement this method to create a custom NMEA message. Returns a that represents this instance. A that represents this instance. Gets the checksum value of the message. Recommended Minimum Called when the message is being loaded. The NMEA message values. Fix Time Gets a value whether the device is active Latitude Longitude Speed over the ground in knots Track angle in degrees True Magnetic Variation Represents an unknown message type Gets the nmea value array. Called when the message is being loaded. The NMEA message values. Generic stream device Initializes a new instance of the class. The stream. Opens the stream asynchronous. Closes the stream asynchronous. The stream. Releases unmanaged and - optionally - managed resources. true to release both managed and unmanaged resources; false to release only unmanaged resources.
================================================ FILE: TestCode/OldCode/Class1.cs ================================================ using System; using System.Threading.Tasks; public namespace RootNamespace { public class BaseClass { public abstract void SomeBaseMethod(); } public class MyClass : IDisposable { MyClass() { } MyClass(int obseleteOverload) { } public void AVoidMethod() { } public Task ATaskReturningGenericMethod() { } public double ProtectedSetProperty { get; protected set; } public double WritableProperty { get; set; } public double ReadOnlyProperty { get; } public double SetOnlyProperty { set; } [Obsolete] public void AlreadyObsoletedMethod(); public double ObsoletedProperty { set; } public void ObsoletedMethod(); public event EventHandler SimpleEvent; public event EventHandler GenericEvent; public event EventHandler ObsoletedEvent { set; } public void Dispose() { } } public class ObsoletedClass {} } ================================================ FILE: TestCode/OldCode/Enum1.cs ================================================ using System; public namespace RootNamespace { public enum ShortEnum : long { Zero=0, One=1, Two=2 } public enum SimpleEnum { Unknown=0, One=1, Two=2 } [Flags] public enum FlagsEnum { Zero = 0, One = 1, Two = 2, Four = 4, Obsolete = 5, All = 255, } } ================================================ FILE: TestCode/OldCode/Interface1.cs ================================================ using System; using System.Threading.Tasks; public namespace RootNamespace { public interface Interface1 { void Method(); } public interface DerivedInterface : Interface1 { void Method2(); } } ================================================ FILE: TestCode/OldCode/NmeaParser.xml ================================================ NmeaParser An abstract generic NMEA device that reads a stream at a decreased pace, mostly used to emulate NMEA input from files and strings. Initializes a new instance of the class. Initializes a new instance of the class. The time to wait between each group of lines being read in milliseconds Gets the stream to perform buffer reads on. Opens the stream asynchronous. Closes the stream asynchronous. The stream. Initializes a new instance of the class. The stream. The read speed in milliseconds. Gets a value indicating whether this instance can read. true if this instance can read; otherwise, false. Gets a value indicating whether this instance can seek. true if this instance can seek; otherwise, false. Gets a value indicating whether this instance can write. true if this instance can write; otherwise, false. Flushes this instance. Gets the length. The length. Gets or sets the position. The position. Reads the specified buffer. The buffer. The offset. The count. Seeks the specified offset. The offset. The origin. Sets the length. The value. Writes the specified buffer to the device. The buffer. The offset. The count. Releases unmanaged and - optionally - managed resources. true to release both managed and unmanaged resources; false to release only unmanaged resources. Total number of messages of this type in this cycle Message number A generic abstract NMEA device Initializes a new instance of the class. Opens the device connection. Creates the stream the NmeaDevice is working on top off. Closes the device. Closes the stream the NmeaDevice is working on top off. The stream. Occurs when an NMEA message is received. Releases unmanaged and - optionally - managed resources. Releases unmanaged and - optionally - managed resources. true to release both managed and unmanaged resources; false to release only unmanaged resources. Gets a value indicating whether this device is open. true if this instance is open; otherwise, false. Event argument for the Gets the nmea message. The nmea message. Gets a value indicating whether this instance is a multi part message. true if this instance is multi part; otherwise, false. Gets the message parts if this is a multi-part message and all message parts has been received. The message parts. A file-based NMEA device reading from a NMEA log file. Initializes a new instance of the class. Initializes a new instance of the class. The time to wait between each group of lines being read in milliseconds Gets the name of the nmea file this device is using. Gets the stream to perform buffer reads on. Position error statistics Called when the message is being loaded. The NMEA message values. UTC of position fix RMS value of the pseudorange residuals; includes carrier phase residuals during periods of RTK (float) and RTK (fixed) processing Error ellipse semi-major axis 1 sigma error, in meters Error ellipse semi-minor axis 1 sigma error, in meters Error ellipse orientation, degrees from true north Latitude 1 sigma error, in meters The error expressed as one standard deviation. Longitude 1 sigma error, in meters The error expressed as one standard deviation. Height 1 sigma error, in meters The error expressed as one standard deviation. Recommended Minimum Called when the message is being loaded. The NMEA message values. Estimated horizontal position error in meters (HPE) Range: 0.0 to 999.9 meters Horizontal Error unit ('M' for Meters) Estimated vertical position error in meters (VPE) Range: 0.0 to 999.9 meters Vertical Error unit ('M' for Meters) Overall spherical equivalent position error (EPE) Range: 0.0 to 999.9 meters Spherical Error unit ('M' for Meters) Altitude Information Altitude unit Unknown Feet Position Fix Dimension Unknown No fix 2D Fix 3D Fix Called when the message is being loaded. The NMEA message values. Current altitude Horizontal Error unit ('M' for Meters) Fix type Bearing Origin to Destination Called when the message is being loaded. The NMEA message values. True Bearing from start to destination Magnetic Bearing from start to destination Name of origin Name of destination Global Positioning System Fix Data Fix quality Invalid GPS Differential GPS Precise Positioning Service Real Time Kinematic (Fixed) Real Time Kinematic (Floating) Estimated Manual input Simulation Called when the message is being loaded. The NMEA message values. Time of day fix was taken Latitude Longitude Fix Quality Number of satellites being tracked Horizontal Dilution of Precision Altitude Altitude units ('M' for Meters) Height of geoid (mean sea level) above WGS84 Altitude units ('M' for Meters) Time since last DGPS update DGPS Station ID Number Geographic position, latitude / longitude Called when the message is being loaded. The NMEA message values. Latitude Longitude Time since last DGPS update Gets a value indicating whether data is active. true if data is active; otherwise, false. Global Positioning System Fix Data Mode selection Auto Manual mode Fix Mode Not available 2D Fix 3D Fix Called when the message is being loaded. The NMEA message values. Mode Mode IDs of SVs used in position fix Dilution of precision Horizontal dilution of precision Vertical dilution of precision Position error statistics Called when the message is being loaded. The NMEA message values. UTC of position fix RMS value of the pseudorange residuals; includes carrier phase residuals during periods of RTK (float) and RTK (fixed) processing Error ellipse semi-major axis 1 sigma error, in meters Error ellipse semi-minor axis 1 sigma error, in meters Error ellipse orientation, degrees from true north Latitude 1 sigma error, in meters The error expressed as one standard deviation. Longitude 1 sigma error, in meters The error expressed as one standard deviation. Height 1 sigma error, in meters The error expressed as one standard deviation. GPS Satellites in view Called when the message is being loaded. The NMEA message values. Total number of messages of this type in this cycle Message number Total number of SVs in view Dilution of precision Returns an enumerator that iterates through the collection. A System.Collections.Generic.IEnumerator{SatelliteVehicle} that can be used to iterate through the collection. Returns an enumerator that iterates through a collection. An System.Collections.IEnumerator object that can be used to iterate through the collection. Satellite vehicle SV PRN number Elevation in degrees, 90 maximum Azimuth, degrees from true north, 000 to 359 Signal-to-Noise ratio, 0-99 dB (-1 when not tracking) Satellite system Satellite system Unknown GPS - Global Positioning System (NAVSTAR) WAAS - Wide Area Augmentation System GLONASS - Globalnaya navigatsionnaya sputnikovaya sistema Recommended minimum navigation information Data status Ok Warning Called when the message is being loaded. The NMEA message values. Data Status Cross-track error (steer left when negative, right when positive) Origin waypoint ID Destination waypoint ID Destination Latitude Destination Longitude Range to destination in nautical miles True bearing to destination Velocity towards destination in knots Arrived (true if arrived) Recommended Minimum Called when the message is being loaded. The NMEA message values. Fix Time Gets a value whether the device is active Latitude Longitude Speed over the ground in knots Track angle in degrees True Magnetic Variation Routes Waypoint tpe Complete list of waypoints List of remaining waypoints Called when the message is being loaded. The NMEA message values. Total number of messages of this type in this cycle Message number Gets the type of the list. Gets the route identifier. Waypoints Returns an enumerator that iterates through the collection. A System.Collections.Generic.IEnumerator{T} that can be used to iterate through the collection. Returns an enumerator that iterates through a collection. An System.Collections.IEnumerator object that can be used to iterate through the collection. Laser Range Measurement Called when the message is being loaded. The NMEA message values. Gets the horizontal vector. Gets the horizontal distance. Gets the units of the value. Gets the horizontal angle. Gets the units of the value. Gets the vertical angle. Gets the units of the value. Gets the slope distance. Gets the units of the value. Laser Range Burden finder Tree Measurement Called when the message is being loaded. The NMEA message values. Gets the height of the tree. Gets the message height of the tree. Gets the units of the value. Gets the tree diameter. Gets the measured tree diameter. Gets the units of the value. Nmea message attribute type used on concrete implementations. Initializes a new instance of the class. The type. Gets or sets the NMEA message type. NMEA Message base class. Parses the specified NMEA message. The NMEA message string. Invalid nmea message: Missing starting character '$' or checksum failure Gets the NMEA message parts. Gets the NMEA type id for the message. Called when the message is being loaded. The NMEA message values. Implement this method to create a custom NMEA message. Returns a that represents this instance. A that represents this instance. Gets the checksum value of the message. Represents an unknown message type Gets the nmea value array. Called when the message is being loaded. The NMEA message values. Generic stream device Initializes a new instance of the class. The stream. Opens the stream asynchronous. Closes the stream asynchronous. The stream. Releases unmanaged and - optionally - managed resources. true to release both managed and unmanaged resources; false to release only unmanaged resources. ================================================ FILE: src/Generator/ArgumentParser.cs ================================================ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Text.RegularExpressions; namespace Generator { static class ArgumentParser { // Based on https://www.codeproject.com/Articles/3111/C-NET-Command-Line-Arguments-Parser public static StringDictionary Parse(string[] arguments) { StringDictionary Parameters = new StringDictionary(); Regex Spliter = new Regex(@"^-{1,2}|^/|=|:", RegexOptions.IgnoreCase | RegexOptions.Compiled); Regex Remover = new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled); string Parameter = null; string[] Parts; // Valid parameters forms: // {-,/,--}param{ ,=,:}((",')value(",')) // Examples: // -param1 value1 --param2 /param3:"Test-:-work" // /param4=happy -param5 '--=nice=--' foreach (string Txt in arguments) { // Look for new parameters (-,/ or --) and a // possible enclosed value (=,:) Parts = Spliter.Split(Txt, 3); switch (Parts.Length) { // Found a value (for the last parameter // found (space separator)) case 1: if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) { Parts[0] = Remover.Replace(Parts[0], "$1"); Parameters.Add(Parameter, Parts[0]); } Parameter = null; } // else Error: no parameter waiting for a value (skipped) break; // Found just a parameter case 2: // The last parameter is still waiting. // With no value, set it to true. if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) Parameters.Add(Parameter, "true"); } Parameter = Parts[1]; break; // Parameter with enclosed value case 3: // The last parameter is still waiting. // With no value, set it to true. if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) Parameters.Add(Parameter, "true"); } Parameter = Parts[1]; // Remove possible enclosing characters (",') if (!Parameters.ContainsKey(Parameter)) { Parts[2] = Remover.Replace(Parts[2], "$1"); Parameters.Add(Parameter, Parts[2]); } Parameter = null; break; } } if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) Parameters.Add(Parameter, "true"); } return Parameters; } } } ================================================ FILE: src/Generator/Generator.csproj ================================================  Exe net6.0 latest true DotnetTool,DotNetCliTool generateomd ./../nupkg dotMorten.OmdGenerator 1.5.2 Morten Nielsen OMD Generator Automatically generates an HTML Document with an object model diagram for your C# library< Copyright © 2018 Morten Nielsen https://github.com/dotMorten/DotNetOMDGenerator https://github.com/dotMorten/DotNetOMDGenerator OMD Diagram CSharp Roslyn true generateomd Major ================================================ FILE: src/Generator/Generators/HtmlOmdFooter.html ================================================ 


Generated with .NET Object Model Diagram Generator

================================================ FILE: src/Generator/Generators/HtmlOmdGenerator.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; namespace Generator.Generators { internal class HtmlOmdGenerator : ICodeGenerator, ICodeDiffGenerator { private System.IO.StreamWriter sw; private List allSymbols; private List oldSymbols; private string currentNamespace; public void Initialize(List allSymbols) => Initialize(allSymbols, null); public void Initialize(List allSymbols, List oldSymbols) { this.allSymbols = allSymbols; this.oldSymbols = oldSymbols; var outLocation = GeneratorSettings.OutputLocation; if (string.IsNullOrEmpty(new System.IO.FileInfo(outLocation).Extension)) outLocation += ".html"; sw = new System.IO.StreamWriter(outLocation); using (var s = typeof(HtmlOmdGenerator).Assembly.GetManifestResourceStream("Generator.Generators.HtmlOmdHeader.html")) { s.CopyTo(sw.BaseStream); } } public void Complete() { if (currentNamespace != null) { //close the last namespace section sw.WriteLine(""); sw.Flush(); } sw.WriteLine("
Command line:
"); sw.WriteLine("
");
            sw.WriteLine("dotnet tool install --global dotMorten.OmdGenerator");
            sw.WriteLine("generateomd " + Environment.CommandLine);
            sw.WriteLine("
"); sw.Flush(); using (var s = typeof(HtmlOmdGenerator).Assembly.GetManifestResourceStream("Generator.Generators.HtmlOmdFooter.html")) { s.CopyTo(sw.BaseStream); } sw.Flush(); sw.Close(); sw.Dispose(); } public void WriteClass(INamedTypeSymbol type) => WriteClass(type, null); public void WriteClass(INamedTypeSymbol type, INamedTypeSymbol oldType = null) { WriteType(type, oldType); } public void WriteType(INamedTypeSymbol type, INamedTypeSymbol oldType) { bool isTypeRemoved = type == null && oldType != null; bool isTypeNew = type != null && oldType == null; if (isTypeRemoved) type = oldType; string kind = ""; switch (type.TypeKind) { case TypeKind.Struct: case TypeKind.Class: kind = "class"; break; case TypeKind.Delegate: kind = "delegate"; break; case TypeKind.Enum: kind = "enum"; break; case TypeKind.Interface: kind = "interface"; break; default: return; //Not supported } //When loading assemblies the kind isn't recognized if(kind == "class" && type.BaseType.GetFullTypeName() =="System.Enum") { kind = "enum"; } var nsname = type.GetFullNamespace(); if (nsname != currentNamespace) { if(currentNamespace != null) { //close the current namespace section sw.WriteLine(""); } sw.WriteLine($"
"); currentNamespace = nsname; sw.WriteLine($"

{nsname}

"); } bool wasObsoleted = type.IsObsolete() && oldType?.IsObsolete() != true; sw.WriteLine($"
"); bool isEmpty = true; var memberBuilder = new StringBuilder(); { //List out members if (type.GetConstructors(oldType).Any()) { isEmpty = false; memberBuilder.AppendLine($"
"); if (type.TypeKind != TypeKind.Delegate) memberBuilder.AppendLine($"

Constructors

"); memberBuilder.AppendLine($"
    "); foreach (var method in type.GetConstructors(oldType)) { var str = FormatMember(method.symbol); if (method.wasRemoved) str = $"{str}"; else if(method.wasObsoleted) str = $"{str}"; memberBuilder.AppendLine($"{GetIcon(method.symbol, str)}"); } memberBuilder.AppendLine("
"); } if (type.GetProperties(oldType).Any()) { isEmpty = false; memberBuilder.AppendLine($"

Properties

    "); foreach (var method in type.GetProperties(oldType)) { var str = FormatMember(method.symbol); if (method.wasRemoved) str = $"{str}"; else if (method.wasObsoleted) str = $"{str}"; memberBuilder.AppendLine($"{GetIcon(method.symbol, str)}"); } memberBuilder.AppendLine("
"); } var methods = type.GetMethods(oldType).ToList(); if (methods.Any()) { isEmpty = false; memberBuilder.AppendLine($"

Methods

    "); foreach (var method in methods) { var str = FormatMember(method.symbol); if (method.wasRemoved) str = $"{str}"; else if (method.wasObsoleted) str = $"{str}"; memberBuilder.AppendLine($"{GetIcon(method.symbol, str)}"); } memberBuilder.AppendLine("
"); } if (type.GetEvents(oldType).Any()) { isEmpty = false; memberBuilder.AppendLine($"

Events

    "); foreach (var method in type.GetEvents(oldType)) { var str = FormatMember(method.symbol); if (method.wasRemoved) str = $"{str}"; else if (method.wasObsoleted) str = $"{str}"; memberBuilder.AppendLine($"{GetIcon(method.symbol, str)}"); } memberBuilder.AppendLine("
"); } if (kind != "enum" && type.GetFields(oldType).Any()) { isEmpty = false; memberBuilder.AppendLine($"

Fields

    "); foreach (var method in type.GetFields(oldType)) { var str = FormatMember(method.symbol); if (method.wasRemoved) str = $"{str}"; else if (method.wasObsoleted) str = $"{str}"; memberBuilder.AppendLine($"{GetIcon(method.symbol, str)}"); } memberBuilder.AppendLine("
"); } if (kind == "enum") { isEmpty = false; memberBuilder.AppendLine("
    "); if (type.TypeKind == TypeKind.Enum) { foreach (var e in type.GetEnums(oldType).OrderBy(f => f.symbol.ConstantValue)) { string str = Briefify(e.symbol); if (e.symbol.HasConstantValue) str += " = " + e.symbol.ConstantValue?.ToString(); if (e.wasRemoved) str = $"{str}"; else if (e.wasObsoleted) str = $"{str}"; memberBuilder.AppendLine($"{GetIcon(e.symbol, str)}"); } } else if(type.TypeKind == TypeKind.Class) { foreach (var e in type.GetFields(oldType).Where(f=>f.symbol.HasConstantValue).OrderBy(f=>f.symbol.ConstantValue)) { if (!e.symbol.HasConstantValue) continue; var str = Briefify(e.symbol) + " = " + e.symbol.ConstantValue?.ToString(); if (e.wasRemoved) str = $"{str}"; else if (e.wasObsoleted) str = $"{str}"; memberBuilder.AppendLine($"{GetIcon(e.symbol, str)}"); } } memberBuilder.AppendLine("
"); } } var symbols = Generator.GetChangedSymbols( type == oldType ? Enumerable.Empty() : type.GetAllNestedTypes(), oldType == null ? Enumerable.Empty() : oldType.GetAllNestedTypes()); if (isEmpty && symbols.Any()) { isEmpty = false; } sw.WriteLine($"
"); //Write class name + Inheritance var brief = type.GetDescription(); sw.Write($"'); if (!isTypeNew && !isTypeRemoved) sw.Write($""); sw.Write(System.Web.HttpUtility.HtmlEncode(type.Name)); if (!isTypeNew && !isTypeRemoved) sw.Write(""); if (type.BaseType != null && (type.BaseType.Name != "Object" || type.BaseType.ToDisplayString() != oldType?.BaseType.ToDisplayString()) && kind != "enum") { if (oldType == null || type.BaseType.ToDisplayString() != oldType.BaseType.ToDisplayString()) { if (oldType != null && oldType.BaseType.Name != "Object") { sw.Write($" : {FormatType(oldType.BaseType)}"); if (type.BaseType.Name != "Object") sw.Write($"{FormatType(type.BaseType)}"); } else if (type.BaseType.Name != "Object") sw.Write($" : {FormatType(type.BaseType)}"); } } else if(kind == "enum") { if(type.TypeKind == TypeKind.Enum) { INamedTypeSymbol enumType = type.EnumUnderlyingType; INamedTypeSymbol oldEnumType = oldType?.EnumUnderlyingType; if (oldEnumType == null || enumType.ToDisplayString() != oldEnumType.ToDisplayString()) { sw.Write(" : "); if (oldEnumType != null) { sw.Write($"{FormatType(oldEnumType)}"); } sw.Write(FormatType(enumType)); } } else if (type.TypeKind == TypeKind.Class) //Happens when analyzing assemblies { var fields = type.GetFields(); var name = fields.FirstOrDefault()?.ConstantValue?.GetType().FullName; var oldname = oldType?.GetFields().FirstOrDefault()?.ConstantValue?.GetType().FullName; if (oldname == null || name != oldname) { sw.Write(" : "); if (oldname != null) { sw.Write($"oldname"); } sw.Write(name); } } } sw.WriteLine(""); //Document interfaces if (type.GetInterfaces(oldType).Any()) { isEmpty = false; sw.Write("
Implements "); int i = 0; foreach(var iface in type.GetInterfaces(oldType)) { if (i > 0) sw.Write(", "); if (iface.wasRemoved) sw.Write(""); sw.Write(FormatType(iface.symbol)); if (iface.wasRemoved) sw.Write(""); i++; } } sw.WriteLine("
"); //End header box sw.Write(memberBuilder.ToString()); if (symbols.Any()) { sw.WriteLine($"

Nested Types

"); foreach (var t in symbols) { WriteType(t.newSymbol, t.oldSymbol); } } sw.WriteLine("
"); sw.Flush(); } private string GetIcon(ISymbol type, string content) { string icon = ""; if (type.DeclaredAccessibility == Accessibility.Public) icon = "pub"; else if (type.DeclaredAccessibility == Accessibility.Protected) icon = "prot"; else if (type.DeclaredAccessibility == Accessibility.Private) icon = "priv"; else if (type.DeclaredAccessibility == Accessibility.ProtectedAndFriend) icon = "privprot"; if (type.Kind == SymbolKind.Method) icon += "method"; else if (type.Kind == SymbolKind.Property) icon += "property"; else if (type.Kind == SymbolKind.Field) icon += "field"; else if (type.Kind == SymbolKind.Event) icon += "event"; if(type.IsStatic && (type.ContainingType?.TypeKind != TypeKind.Enum && !(type.ContainingType?.TypeKind == TypeKind.Class && type.ContainingType?.BaseType?.GetFullTypeName() == "System.Enum"))) { content = "" + content; } if (icon == "") return content; return $"
  • {content}
  • "; } public void WriteEnum(INamedTypeSymbol enm) => WriteEnum(enm, null); public void WriteEnum(INamedTypeSymbol enm, INamedTypeSymbol oldType = null) { WriteType(enm, oldType); } public void WriteInterface(INamedTypeSymbol iface) => WriteInterface(iface, null); public void WriteInterface(INamedTypeSymbol iface, INamedTypeSymbol oldType = null) { WriteType(iface, oldType); } public void WriteDelegate(INamedTypeSymbol del) => WriteDelegate(del, null); public void WriteDelegate(INamedTypeSymbol del, INamedTypeSymbol oldDel = null) { WriteType(del, oldDel); } private string FormatType(ITypeSymbol type) { var f = SymbolDisplayFormat.MinimallyQualifiedFormat; f.AddGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeParameters); var parts = type.ToDisplayParts(f); if (parts.Length > 1) { string t = ""; foreach (var p in parts) { if (p.Kind == SymbolDisplayPartKind.Punctuation || p.Kind == SymbolDisplayPartKind.Space) t += System.Web.HttpUtility.HtmlEncode(p.ToString()); else if (p.Symbol is ITypeSymbol its) t += LinkifyType(its, false); else { } } return t; } else { return LinkifyType(type); } } private string LinkifyType(ITypeSymbol type, bool includeGeneric = true) { if(type is INamedTypeSymbol nts && nts.IsGenericType && !includeGeneric) { type = nts.OriginalDefinition; } var name = includeGeneric ? type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) : type.Name; if (allSymbols.Contains(type)) return $"{System.Web.HttpUtility.HtmlEncode(name)}"; else return Briefify(type, name); } private static string AccessorToString(Accessibility a) { switch(a) { case Accessibility.Public: return "public"; case Accessibility.Private: return "private"; case Accessibility.Internal: return "internal"; case Accessibility.Protected: return "protected"; case Accessibility.ProtectedOrInternal: return GeneratorSettings.ShowInternalMembers ? "protected internal" : "protected"; case Accessibility.ProtectedAndInternal: return "private protected"; default: return string.Empty; } } private string FormatMember(ISymbol member) { var brief = member.GetDescription(); var name = member.Name; if (name == ".ctor") { name = member.ContainingType.Name; } name = Briefify(member, name); if (member is IPropertySymbol p) { name += " { "; if (p.GetMethod != null && ((p.GetMethod.DeclaredAccessibility == Accessibility.Public || p.GetMethod.DeclaredAccessibility == Accessibility.Protected || p.GetMethod.DeclaredAccessibility == Accessibility.ProtectedOrInternal) || (GeneratorSettings.ShowInternalMembers && p.GetMethod.DeclaredAccessibility == Accessibility.Internal || p.GetMethod.DeclaredAccessibility == Accessibility.ProtectedAndInternal) || (GeneratorSettings.ShowPrivateMembers && p.GetMethod.DeclaredAccessibility == Accessibility.Private))) { if(p.DeclaredAccessibility != p.GetMethod.DeclaredAccessibility) { name += AccessorToString(p.GetMethod.DeclaredAccessibility) + " "; } name += "get; "; } if (p.SetMethod != null && ((p.SetMethod.DeclaredAccessibility == Accessibility.Public || p.SetMethod.DeclaredAccessibility == Accessibility.Protected || p.SetMethod.DeclaredAccessibility == Accessibility.ProtectedOrInternal) || (GeneratorSettings.ShowInternalMembers && p.SetMethod.DeclaredAccessibility == Accessibility.Internal || p.SetMethod.DeclaredAccessibility == Accessibility.ProtectedAndInternal) || (GeneratorSettings.ShowPrivateMembers && p.SetMethod.DeclaredAccessibility == Accessibility.Private))) { if (p.DeclaredAccessibility != p.SetMethod.DeclaredAccessibility) { name += AccessorToString(p.SetMethod.DeclaredAccessibility) + " "; } name += "set; "; } name += "} : " + FormatType(p.Type); } else if (member is IMethodSymbol m) { if (m.TypeArguments.Any()) { name += System.Web.HttpUtility.HtmlEncode("<" + string.Join(", ", m.TypeArguments.Select(t => t.ToDisplayString())) + ">"); } name += "("; name += string.Join(", ", m.Parameters.Select(pr => FormatType(pr.Type) + " " + Briefify(pr) + (pr.HasExplicitDefaultValue ? (" = " + (pr.ExplicitDefaultValue?.ToString() ?? "null")) : ""))); name += ")"; if (!m.ReturnsVoid) { name += " : " + FormatType(m.ReturnType); } } else if (member is IEventSymbol e) { name += " : " + FormatType(e.Type); } else if (member is IFieldSymbol f) { name += " : " + FormatType(f.Type); } return name; } private static string Briefify(ISymbol symbol, string content = null) { if (content == null) content = symbol.Name; var brief = symbol.GetDescription(); if (!string.IsNullOrEmpty(brief)) return $"{System.Web.HttpUtility.HtmlEncode(content)}"; return System.Web.HttpUtility.HtmlEncode(content); } } } ================================================ FILE: src/Generator/Generators/HtmlOmdHeader.html ================================================  OMD Generated with .NET Object Model Diagram Generator

    ================================================ FILE: src/Generator/Generators/MarkdownGenerator.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; namespace Generator.Generators { internal class MarkdownGenerator : ICodeGenerator, ICodeDiffGenerator { private System.IO.StreamWriter sw; private List allSymbols; private List oldSymbols; private string currentNamespace; public void Initialize(List allSymbols) => Initialize(allSymbols, null); public void Initialize(List allSymbols, List oldSymbols) { this.allSymbols = allSymbols; this.oldSymbols = oldSymbols; var outLocation = GeneratorSettings.OutputLocation; if (string.IsNullOrEmpty(new System.IO.FileInfo(outLocation).Extension)) outLocation += ".md"; sw = new System.IO.StreamWriter(outLocation); WriteLine("
    ", 0);
            }
    
            public void Complete()
            {
                if (currentNamespace != null)
                {
                    //close the last namespace section
                    WriteLine("}", 0);
                    WriteLine("
    ", 0); WriteLine("Generated with (.NET Object Model Diagram Generator)[https://github.com/dotMorten/DotNetOMDGenerator]", 0); sw.Flush(); } sw.Flush(); sw.Close(); sw.Dispose(); } public void WriteClass(INamedTypeSymbol type) => WriteType(type, null, false); public void WriteClass(INamedTypeSymbol type, INamedTypeSymbol oldType = null) { WriteType(type, oldType, true); } private void WriteLine(string line, int indent) { if (!string.IsNullOrEmpty(line)) { for (int i = 0; i < indent; i++) { line = "\t" + line.Replace("\n", "\n\t"); } line = line.Replace("\n", "\n"); line = line.Replace("\t", " "); sw.Write(line); } sw.WriteLine(); } private const string RemoveStart = ""; private const string RemoveEnd = ""; private const string AddedStart = ""; private const string AddedEnd = ""; public void WriteType(INamedTypeSymbol type, INamedTypeSymbol oldType, bool isComparison, int indent = 0) { bool isTypeRemoved = type == null && oldType != null; bool isTypeNew = type != null && oldType == null && isComparison; if (isTypeRemoved) type = oldType; string kind = ""; switch (type.TypeKind) { case TypeKind.Struct: case TypeKind.Class: if (type.BaseType.GetFullTypeName() == "System.Enum") kind = "enum"; //When loading assemblies the enum kind isn't recognized else { kind = "class"; if (type.IsSealed && (oldType == null || oldType.IsSealed)) kind = "sealed " + kind; else if (type.IsSealed && !oldType.IsSealed) kind = $"{AddedStart}sealed{AddedEnd} {kind}"; else if (!type.IsSealed && oldType != null && oldType.IsSealed) kind = $"{RemoveStart}sealed{RemoveEnd} {kind}"; if (type.IsStatic && (oldType == null || oldType.IsStatic)) kind = "static " + kind; else if (type.IsStatic && !oldType.IsStatic) kind = $"{AddedStart}static{AddedEnd} {kind}"; else if (!type.IsStatic && oldType != null && oldType.IsStatic) kind = $"{RemoveStart}static{RemoveEnd} {kind}"; } break; case TypeKind.Delegate: kind = "delegate"; break; case TypeKind.Enum: kind = "enum"; break; case TypeKind.Interface: kind = "interface"; break; default: return; //Not supported } var nsname = type.GetFullNamespace(); if (nsname != currentNamespace) { if (currentNamespace != null) { //close the current namespace section WriteLine("}", indent); } WriteLine($"namespace {nsname}\n{{", indent); currentNamespace = nsname; } string className = AccessorToString(type.DeclaredAccessibility) + " " + kind + " " + type.Name; var symbols = Generator.GetChangedSymbols( type == oldType ? Enumerable.Empty() : type.GetAllNestedTypes(), oldType == null ? Enumerable.Empty() : oldType.GetAllNestedTypes()); if (type.BaseType != null && (type.BaseType.Name != "Object" || type.BaseType.ToDisplayString() != oldType?.BaseType.ToDisplayString()) && kind != "enum") { if (oldType == null || type.BaseType.ToDisplayString() != oldType.BaseType.ToDisplayString()) { if (oldType != null && oldType.BaseType.Name != "Object" && !isTypeRemoved) { className += $" : {RemoveStart}{FormatType(oldType.BaseType)}{RemoveEnd}"; //removed baseclass if (type.BaseType.Name != "Object") className += $"{FormatType(type.BaseType)}"; } if (type.BaseType.Name != "Object") { if (isComparison && !isTypeNew) className += $" : {AddedStart}{FormatType(type.BaseType)}{AddedEnd}"; //new baseclass else className += $" : {FormatType(type.BaseType)}"; } } } else if (kind == "enum") { if (type.TypeKind == TypeKind.Enum) { INamedTypeSymbol enumType = type.EnumUnderlyingType; INamedTypeSymbol oldEnumType = oldType?.EnumUnderlyingType; if (oldEnumType == null || enumType.ToDisplayString() != oldEnumType.ToDisplayString()) { className += " : "; if (oldEnumType != null && !isTypeRemoved) { className += $"{RemoveStart}{FormatType(oldEnumType)}{RemoveEnd}{AddedStart}{FormatType(enumType)}{AddedEnd}"; //removed baseclass } else if (oldEnumType == null && isComparison && !isTypeNew) className += $"{AddedStart}{FormatType(enumType)}{AddedEnd}"; //new baseclass else className += FormatType(enumType); } } else if (type.TypeKind == TypeKind.Class) //Happens when analyzing assemblies { var fields = type.GetFields(); var enumType = fields.FirstOrDefault()?.ConstantValue?.GetType().FullName; var oldEnumType = oldType?.GetFields().FirstOrDefault()?.ConstantValue?.GetType().FullName; if (oldEnumType == null || enumType != oldEnumType) { className += " : "; if (oldEnumType != null && !isTypeRemoved) { className += $"{RemoveStart}{oldEnumType}{RemoveEnd}"; //removed baseclass } else if (oldEnumType == null && isComparison && !isTypeNew) className += $"{AddedStart}{enumType}{AddedEnd}"; //new baseclass else className += enumType; } } } //Document interfaces if (type.GetInterfaces(oldType).Any()) { foreach (var iface in type.GetInterfaces(oldType)) { if (className.Contains(" : ")) className += ", "; else className += " : "; var typeName = FormatType(iface.symbol); if (iface.wasRemoved && !isTypeRemoved) typeName = $"{RemoveStart}{typeName}{RemoveEnd}"; else if (isComparison && !isTypeNew) className += $"{AddedStart}{typeName}{AddedEnd}"; else className += typeName; } } if (isTypeRemoved) { WriteLine($"{RemoveStart}{className} {{ ... }}{RemoveEnd}", indent + 1); return; } WriteLine($"{(isTypeNew && isComparison ? AddedStart : "")}{className}", indent + 1); WriteLine("{", indent + 1); //Begin class //List out members if (type.GetConstructors(oldType).Any()) { foreach (var method in type.GetConstructors(oldType)) { var str = FormatMember(method.symbol); if (method.wasRemoved) str = $"{RemoveStart}{str}{RemoveEnd}"; else if (isComparison && !isTypeNew) str = $"{AddedStart}{str}{AddedEnd}"; WriteLine(str, indent + 2); } } if (type.GetProperties(oldType).Any()) { foreach (var method in type.GetProperties(oldType)) { var str = FormatMember(method.symbol); if (method.wasRemoved) str = $"{RemoveStart}{str}{RemoveEnd}"; else if (isComparison && !isTypeNew) str = $"{AddedStart}{str}{AddedEnd}"; WriteLine(str, indent + 2); } } if (type.GetMethods(oldType).Any()) { foreach (var method in type.GetMethods(oldType)) { var str = FormatMember(method.symbol); if (method.wasRemoved) str = $"{RemoveStart}{str}{RemoveEnd}"; else if (isComparison && !isTypeNew) str = $"{AddedStart}{str}{AddedEnd}"; WriteLine(str, indent + 2); } } if (type.GetEvents(oldType).Any()) { foreach (var method in type.GetEvents(oldType)) { var str = FormatMember(method.symbol) + ";"; if (method.wasRemoved) str = $"{RemoveStart}{str}{RemoveEnd}"; else if (isComparison && !isTypeNew) str = $"{AddedStart}{str}{AddedEnd}"; WriteLine(str, indent + 2); } } if (kind != "enum" && type.GetFields(oldType).Any()) { foreach (var method in type.GetFields(oldType)) { var str = FormatMember(method.symbol); if (method.wasRemoved) str = $"{RemoveStart}{str}{RemoveEnd}"; else if (isComparison && !isTypeNew) str = $"{AddedStart}{str}{AddedEnd}"; WriteLine(str, indent + 2); } } if (kind == "enum") { if (type.TypeKind == TypeKind.Enum) { foreach (var e in type.GetEnums(oldType).OrderBy(f => f.symbol.ConstantValue)) { string str = Briefify(e.symbol); if (e.symbol.HasConstantValue) str += " = " + e.symbol.ConstantValue?.ToString(); if (e.wasRemoved) str = $"{RemoveStart}{str}{RemoveEnd}"; else if (isComparison && !isTypeNew) str = $"{AddedStart}{str}{AddedEnd}"; WriteLine(str + ",", indent + 2); } } else if (type.TypeKind == TypeKind.Class) { foreach (var e in type.GetFields(oldType).Where(f => f.symbol.HasConstantValue).OrderBy(f => f.symbol.ConstantValue)) { if (!e.symbol.HasConstantValue) continue; string str = Briefify(e.symbol) + " = " + e.symbol.ConstantValue?.ToString(); if (e.wasRemoved) str = $"{RemoveStart}{str}{RemoveEnd}"; else if (isComparison && !isTypeNew) str = $"{AddedStart}{str}{AddedEnd}"; WriteLine(str + ",", indent + 2); } } } if (symbols.Any()) { WriteLine(null, 0); foreach (var t in symbols) { WriteType(t.newSymbol, t.oldSymbol, isComparison && !isTypeNew, indent + 1); } } WriteLine("}" + (isTypeNew && isComparison ? AddedEnd:""), indent + 1); //EndClass sw.Flush(); } public void WriteEnum(INamedTypeSymbol enm) => WriteType(enm, null, false); public void WriteEnum(INamedTypeSymbol enm, INamedTypeSymbol oldType = null) { WriteType(enm, oldType, true); } public void WriteInterface(INamedTypeSymbol iface) => WriteType(iface, null, false); public void WriteInterface(INamedTypeSymbol iface, INamedTypeSymbol oldType = null) { WriteType(iface, oldType, true); } public void WriteDelegate(INamedTypeSymbol del) => WriteType(del, null, false); public void WriteDelegate(INamedTypeSymbol del, INamedTypeSymbol oldDel = null) { WriteType(del, oldDel, true); } private string FormatType(ITypeSymbol type) { var f = SymbolDisplayFormat.MinimallyQualifiedFormat; f.AddGenericsOptions(SymbolDisplayGenericsOptions.IncludeTypeParameters); var parts = type.ToDisplayParts(f); if (parts.Length > 1) { string t = ""; foreach (var p in parts) { if (p.Kind == SymbolDisplayPartKind.Punctuation || p.Kind == SymbolDisplayPartKind.Space) t += p; // System.Web.HttpUtility.HtmlEncode(p.ToString()); else if (p.Symbol is ITypeSymbol its) t += LinkifyType(its, false); else { } } return t; } else { return LinkifyType(type); } } private string LinkifyType(ITypeSymbol type, bool includeGeneric = true) { if (type is INamedTypeSymbol nts && nts.IsGenericType && !includeGeneric) { type = nts.OriginalDefinition; } var name = includeGeneric ? type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) : type.Name; //if (allSymbols.Contains(type)) // return $"{System.Web.HttpUtility.HtmlEncode(name)}"; //else return Briefify(type, name); } private static string AccessorToString(Accessibility a) { switch (a) { case Accessibility.Public: return "public"; case Accessibility.Private: return "private"; case Accessibility.Internal: return "internal"; case Accessibility.Protected: return "protected"; case Accessibility.ProtectedOrInternal: return GeneratorSettings.ShowInternalMembers ? "protected internal" : "protected"; case Accessibility.ProtectedAndInternal: return "private protected"; default: return string.Empty; } } private string FormatMember(ISymbol member) { var brief = member.GetDescription(); var name = member.Name; if (name == ".ctor") { name = member.ContainingType.Name; } name = Briefify(member, name); string accessor = AccessorToString(member.DeclaredAccessibility); if (member is IPropertySymbol p) { name += " { "; if (p.GetMethod != null && ((p.GetMethod.DeclaredAccessibility == Accessibility.Public || p.GetMethod.DeclaredAccessibility == Accessibility.Protected || p.GetMethod.DeclaredAccessibility == Accessibility.ProtectedOrInternal) || (GeneratorSettings.ShowInternalMembers && p.GetMethod.DeclaredAccessibility == Accessibility.Internal || p.GetMethod.DeclaredAccessibility == Accessibility.ProtectedAndInternal) || (GeneratorSettings.ShowPrivateMembers && p.GetMethod.DeclaredAccessibility == Accessibility.Private))) { if (p.DeclaredAccessibility != p.GetMethod.DeclaredAccessibility) { name += AccessorToString(p.GetMethod.DeclaredAccessibility) + " "; } name += "get; "; } if (p.SetMethod != null && ((p.SetMethod.DeclaredAccessibility == Accessibility.Public || p.SetMethod.DeclaredAccessibility == Accessibility.Protected || p.SetMethod.DeclaredAccessibility == Accessibility.ProtectedOrInternal) || (GeneratorSettings.ShowInternalMembers && p.SetMethod.DeclaredAccessibility == Accessibility.Internal || p.SetMethod.DeclaredAccessibility == Accessibility.ProtectedAndInternal) || (GeneratorSettings.ShowPrivateMembers && p.SetMethod.DeclaredAccessibility == Accessibility.Private))) { if (p.DeclaredAccessibility != p.SetMethod.DeclaredAccessibility) { name += AccessorToString(p.SetMethod.DeclaredAccessibility) + " "; } name += "set; "; } name = FormatType(p.Type) + " " + name + "}"; } else if (member is IMethodSymbol m) { if (m.TypeArguments.Any()) { name += "<" + string.Join(", ", m.TypeArguments.Select(t => t.ToDisplayString())) + ">"; } name += "("; name += string.Join(", ", m.Parameters.Select(pr => FormatType(pr.Type) + " " + Briefify(pr) + (pr.HasExplicitDefaultValue ? (" = " + (pr.ExplicitDefaultValue?.ToString() ?? "null")) : ""))); name += ");"; if (!m.ReturnsVoid) { name = FormatType(m.ReturnType) + " " + name; } } else if (member is IEventSymbol e) { name = FormatType(e.Type) + " " + name; } else if (member is IFieldSymbol f) { name = FormatType(f.Type) + " " + name; } if (member.ContainingType.TypeKind == TypeKind.Interface) return name; //Don't add accessor to interface members return accessor + " " + name; } private static string Briefify(ISymbol symbol, string content = null) { if (content == null) content = symbol.Name; return content; //var brief = symbol.GetDescription(); //if (!string.IsNullOrEmpty(brief)) // return $"{System.Web.HttpUtility.HtmlEncode(content)}"; //return System.Web.HttpUtility.HtmlEncode(content); } } } ================================================ FILE: src/Generator/Generators/OMDGenerator.cs ================================================ using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; namespace Generator.Generators { internal class OMDGenerator : ICodeGenerator { private static SolidBrush BackgroundClassBrush = new SolidBrush(Color.FromArgb(255, 211, 220, 239)); private static SolidBrush BackgroundInterfaceBrush = new SolidBrush(Color.FromArgb(255, 231, 240, 220)); private static SolidBrush BackgroundEnumBrush = new SolidBrush(Color.FromArgb(255, 221, 214, 239)); private static SolidBrush BackgroundGroupBrush = new SolidBrush(Color.FromArgb(255, 240, 242, 239)); private static Font MemberFont = new System.Drawing.Font("Arial", 16); private static Font HeaderFont = new System.Drawing.Font("Arial", 20, FontStyle.Bold); private static Pen BlackPen = new Pen(Color.Black, 1); private const int groupHeight = 47; private const int headerHeight = 100; private const int lineSpacing = 12; private const int MemberIndent = 75; public void WriteClass(INamedTypeSymbol type) =>RenderOMD(type); public void WriteDelegate(INamedTypeSymbol type) => RenderOMD(type); public void WriteEnum(INamedTypeSymbol enm) => RenderOMD(enm); public void WriteInterface(INamedTypeSymbol iface) => RenderOMD(iface); private void RenderOMD(INamedTypeSymbol type) { using (Bitmap bitmap = new System.Drawing.Bitmap(2000, 2000)) { int y = 0; int startHeight = 0; double width = 200; //MinWidth using (var bmp = System.Drawing.Graphics.FromImage(bitmap)) { bmp.Clear(Color.Transparent); if (type.Interfaces.Any()) { bmp.DrawEllipse(BlackPen, 40, 0, 24, 24); y += 5; foreach (var iface in type.Interfaces) { width = Math.Max(width, bmp.MeasureString(iface.Name, HeaderFont).Width + 75); bmp.DrawString(iface.Name, MemberFont, Brushes.Black, 75, y); y += (int)(MemberFont.Size + lineSpacing); } y += lineSpacing; bmp.DrawLine(BlackPen, 52, 24, 52, y); } startHeight = y; var bbrush = BackgroundClassBrush; if (type.TypeKind == TypeKind.Enum) bbrush = BackgroundEnumBrush; else if (type.TypeKind == TypeKind.Interface) bbrush = BackgroundInterfaceBrush; bmp.FillRectangle(bbrush, 0, y, bitmap.Width, headerHeight); width = Math.Max(width, bmp.MeasureString(type.Name, HeaderFont).Width + 10); bmp.DrawString(type.Name, HeaderFont, Brushes.Black, 10, 18 + y); string typeDesc = ""; if (type.TypeKind == TypeKind.Class) typeDesc = type.IsAbstract ? "Abstract " : "" + "Class"; else if (type.TypeKind == TypeKind.Interface) typeDesc = "Interface"; else if (type.TypeKind == TypeKind.Enum) typeDesc = "Enum"; bmp.DrawString(typeDesc, MemberFont, Brushes.Black, 10, 18 + y + HeaderFont.Size + lineSpacing); if (type.BaseType != null && type.BaseType.Name != "Object" && type.TypeKind != TypeKind.Enum) bmp.DrawString("→ " + type.BaseType.Name, MemberFont, Brushes.Black, 10, 18 + y + HeaderFont.Size + lineSpacing * 2 + MemberFont.Size); y += headerHeight; bmp.DrawLine(BlackPen, 0, y, bitmap.Width, y); Action> RenderMembers = (n, m) => { if (m.Any()) { bmp.FillRectangle(BackgroundGroupBrush, 0, y, bitmap.Width, groupHeight); var size = bmp.MeasureString(n, new Font("Arial", 18)); width = Math.Max(width, size.Width + 25); bmp.DrawString(n, new Font("Arial", 18), Brushes.Black, 25, y + (groupHeight - size.Height)/2); y += groupHeight + lineSpacing; foreach (var method in m) { var str = FormatMember(method); width = Math.Max(width, bmp.MeasureString(str, MemberFont).Width + MemberIndent); bmp.DrawString(str, MemberFont, Brushes.Black, MemberIndent, y); y += (int)(MemberFont.Size + lineSpacing); } y += lineSpacing; } }; RenderMembers("Constructors", type.GetConstructors().OfType()); RenderMembers("Properties", type.GetProperties().OfType()); RenderMembers("Methods", type.GetMethods().OfType()); RenderMembers("Events", type.GetEvents().OfType()); if(type.TypeKind == TypeKind.Enum) { y += lineSpacing; foreach(var e in type.GetEnums()) { string str = e.Name; width = Math.Max(width, bmp.MeasureString(str, MemberFont).Width + 25); bmp.DrawString(str, MemberFont, Brushes.Black, 25, y); y += (int)(MemberFont.Size + lineSpacing); } } bmp.Flush(); } int padding = 10; using (Bitmap bitmap2 = new System.Drawing.Bitmap((int)width + 10 + 2* padding, (int)y + 10 + 2* padding)) { using (var bmp2 = System.Drawing.Graphics.FromImage(bitmap2)) { bmp2.Clear(Color.White); bmp2.DrawImageUnscaledAndClipped(bitmap, new Rectangle(padding, padding, bitmap2.Width - 2 * padding, bitmap2.Height - 2 * padding)); bmp2.DrawRectangle(BlackPen, padding, startHeight+padding, (float)bitmap2.Width - 21, bitmap2.Height - startHeight - 21); } bitmap2.Save($"{type.ContainingNamespace.GetFullNamespace()}.{type.Name}.png"); } } } private string FormatMember(ISymbol member) { string name = member.Name; if (member.DeclaredAccessibility != Accessibility.Public) { name = member.DeclaredAccessibility.ToString().ToLower() + " " + name; } if (member is IPropertySymbol) { var p = (IPropertySymbol)member; name += " { "; if(p.IsReadable()) { if (p.GetMethod.DeclaredAccessibility < member.DeclaredAccessibility) { name += p.SetMethod.DeclaredAccessibility.ToString() + " "; } name += "get; "; } if (p.IsSettable()) { if (p.SetMethod.DeclaredAccessibility < member.DeclaredAccessibility) { name += p.SetMethod.DeclaredAccessibility.ToString() + " "; } name += "set; "; } name += "} : " + p.Type.Name; } else if(member is IMethodSymbol) { var m = (member as IMethodSymbol); name += "("; name += string.Join(", ", m.Parameters.Select(p => p.Type.Name + " " + p.Name)); name += ")"; if (!m.ReturnsVoid) { name += " : " + m.ReturnType.Name; } } else if (member is IEventSymbol) { var m = (member as IEventSymbol); name += " : " + m.Type.Name; } return name; } public void Initialize(List allSymbols) { } public void Complete() { } } } ================================================ FILE: src/Generator/ICodeGenerator.cs ================================================ using System; using System.Collections.Generic; using System.Text; using Microsoft.CodeAnalysis; namespace Generator { interface ICodeGenerator { void Initialize(List allSymbols); void WriteClass(INamedTypeSymbol type); void WriteInterface(INamedTypeSymbol iface); void WriteEnum(INamedTypeSymbol enm); void WriteDelegate(INamedTypeSymbol type); void Complete(); } interface ICodeDiffGenerator { void Initialize(List allSymbols, List oldSymbols); void WriteClass(INamedTypeSymbol type, INamedTypeSymbol oldType); void WriteInterface(INamedTypeSymbol iface, INamedTypeSymbol oldIface); void WriteEnum(INamedTypeSymbol enm, INamedTypeSymbol oldEnm); void WriteDelegate(INamedTypeSymbol del, INamedTypeSymbol oldDel); void Complete(); } } ================================================ FILE: src/Generator/Program.cs ================================================ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using NuGet.Protocol.Core.Types; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace Generator { internal static class GeneratorSettings { public static bool ShowPrivateMembers { get; set; } = false; public static bool ShowInternalMembers { get; set; } = false; public static string OutputLocation { get; set; } = "./"; } class Program { static async Task Main(string[] args) { Console.WriteLine("*********************** Object Model Generator ***********************"); var arg = ArgumentParser.Parse(args); List generators = new List(); if (arg.ContainsKey("format")) { var formats = arg["format"].Split(';', StringSplitOptions.RemoveEmptyEntries); foreach (var format in formats) if (format == "md") generators.Add(new Generators.MarkdownGenerator()); else if (format == "html") generators.Add(new Generators.HtmlOmdGenerator()); else { Console.WriteLine("Invalid format parameter."); WriteUsage(); return; } } if(!generators.Any()) { generators.Add(new Generators.HtmlOmdGenerator()); } if (!arg.ContainsKey("source") && !arg.ContainsKey("assemblies") && !arg.ContainsKey("nuget")) { WriteUsage(); return; } GeneratorSettings.ShowPrivateMembers = arg.ContainsKey("showPrivate"); GeneratorSettings.ShowInternalMembers = arg.ContainsKey("showInternal"); if(arg.ContainsKey("output")) GeneratorSettings.OutputLocation = arg["output"]; List filters = arg.ContainsKey("exclude") ? arg["exclude"].Split(';', StringSplitOptions.RemoveEmptyEntries).Select(f=>CreateFilter(f)).ToList() : new List(); if(arg.ContainsKey("regexfilter")) filters.Add(new Regex(arg["regexfilter"])); string[] source = arg.ContainsKey("source") ? arg["source"].Split(';', StringSplitOptions.RemoveEmptyEntries) : new string[] { }; string[] oldSource = arg.ContainsKey("compareSource") ? arg["compareSource"].Split(';', StringSplitOptions.RemoveEmptyEntries) : null; string[] preprocessors = arg.ContainsKey("preprocessors") ? arg["preprocessors"].Split(';', StringSplitOptions.RemoveEmptyEntries) : null; string[] assemblies = arg.ContainsKey("assemblies") ? arg["assemblies"].Split(';', StringSplitOptions.RemoveEmptyEntries) : new string[] { }; string[] compareAssemblies = arg.ContainsKey("compareAssemblies") ? arg["compareAssemblies"].Split(';', StringSplitOptions.RemoveEmptyEntries) : null; string[] referenceAssemblies = arg.ContainsKey("referenceAssemblies") ? arg["referenceAssemblies"].Split(';', StringSplitOptions.RemoveEmptyEntries) : null; string[] filterTypes = arg.ContainsKey("filter") ? arg["filter"].Split(';', StringSplitOptions.RemoveEmptyEntries) : null; string[] nugetPackages = arg.ContainsKey("nuget") ? arg["nuget"].Split(';', StringSplitOptions.RemoveEmptyEntries) : null; string[] compareNugetPackages = arg.ContainsKey("compareNuget") ? arg["compareNuget"].Split(';', StringSplitOptions.RemoveEmptyEntries) : null; string tfm = arg.ContainsKey("tfm") ? arg["tfm"] : null; // Fetch nuget packages if (nugetPackages != null && nugetPackages.Length > 0) { var nugetAssemblies = await ParseNugets(nugetPackages, tfm); if (nugetAssemblies is null) return; Console.WriteLine($"Found {nugetAssemblies.Length} assemblies in nuget packages"); assemblies = assemblies == null ? nugetAssemblies : assemblies.Concat(nugetAssemblies).ToArray(); } if (compareNugetPackages != null && compareNugetPackages.Length > 0) { var nugetAssemblies = await ParseNugets(compareNugetPackages, tfm); if (nugetAssemblies is null) return; Console.WriteLine($"Found {nugetAssemblies.Length} assemblies in nuget packages"); compareAssemblies = compareAssemblies == null ? nugetAssemblies : compareAssemblies.Concat(nugetAssemblies).ToArray(); } var g = new Generator(generators); //Set up output filename if (string.IsNullOrEmpty(GeneratorSettings.OutputLocation)) GeneratorSettings.OutputLocation = "./"; var fi = new System.IO.FileInfo(GeneratorSettings.OutputLocation); if (!fi.Directory.Exists) throw new System.IO.DirectoryNotFoundException(fi.Directory.FullName); if (fi.Attributes == System.IO.FileAttributes.Directory) GeneratorSettings.OutputLocation = System.IO.Path.Combine(GeneratorSettings.OutputLocation, "OMD"); if (oldSource != null || compareAssemblies != null) await g.ProcessDiffs(oldSource, source, compareAssemblies, assemblies, preprocessors, filters.ToArray(), referenceAssemblies, filterTypes); else await g.Process(source, assemblies, preprocessors, filters.ToArray(), referenceAssemblies, filterTypes); if(System.Diagnostics.Debugger.IsAttached) Console.ReadKey(); } static List resources; private async static Task ParseNugets(string[] nugetPackages, string tfm) { if (string.IsNullOrEmpty(tfm)) { Console.WriteLine("A target framework identifier is required with nuget parameter. For example: '-tfm net8.0-windows10.0.19041.0'"); return null; } if (resources is null) { var settings = NuGet.Configuration.Settings.LoadDefaultSettings(null); var sources = NuGet.Configuration.SettingsUtility.GetEnabledSources(settings); resources = new List(); foreach (var source in sources) { List> providers = new List>(); providers.AddRange(Repository.Provider.GetCoreV3()); // Add v3 API support SourceRepository repository = new SourceRepository(source, providers); FindPackageByIdResource resource = await repository.GetResourceAsync(); resources.Add(resource); } } List nugetAssemblies = new List(); // https://www.nuget.org/api/v2/package/Newtonsoft.Json/13.0.3 foreach (var package in nugetPackages) { if (!package.Contains(":")) { Console.WriteLine($"Invalid nuget identifier {package}. Please use the format `nugetid:version`, for example 'Newtonsoft.Json:13.0.3'"); return null; } string[] id = package.Split(':', 2, StringSplitOptions.None); if (id.Length != 2) { Console.WriteLine($"Invalid nuget identifier {package}"); return null; } NuGet.Versioning.NuGetVersion version; if (!NuGet.Versioning.NuGetVersion.TryParse(id[1], out version)) { Console.WriteLine($"Invalid nuget version {id[1]}"); return null; } //var f = NuGet.Frameworks.AssetTargetFallbackFramework.ParseFrameworkName(tfm, new NuGet.Frameworks.DefaultFrameworkNameProvider()); var f = NuGet.Frameworks.NuGetFramework.Parse(tfm, new NuGet.Frameworks.DefaultFrameworkNameProvider()); Console.WriteLine($"Getting NuGet package {package}..."); MemoryStream resultStream = null; foreach (var resource in resources) { var exists = await resource.DoesPackageExistAsync(id[0], version, new SourceCacheContext(), NuGet.Common.NullLogger.Instance, System.Threading.CancellationToken.None); if (!exists) { continue; } MemoryStream packageStream = new MemoryStream(); bool result = await resource.CopyNupkgToStreamAsync( id[0], version, packageStream, new SourceCacheContext(), NuGet.Common.NullLogger.Instance, System.Threading.CancellationToken.None); if (result) { resultStream = packageStream; resultStream.Seek(0, SeekOrigin.Begin); break; } else { packageStream.Dispose(); } } if (resultStream is null) { Console.WriteLine($"'{package}' not found"); return null; } using var packageReader = new NuGet.Packaging.PackageArchiveReader(resultStream); var libs = (await packageReader.GetLibItemsAsync(CancellationToken.None)).ToList(); var nearest = NuGet.Frameworks.NuGetFrameworkExtensions.GetNearest(libs, f); if (nearest is null) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Warning: No compatible target framework libs found for '{tfm}' in '{package}'"); Console.ResetColor(); resultStream.Dispose(); continue; } var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); packageReader.CopyFiles(path, nearest.Items.Where(i => !i.EndsWith("/")), (string sourceFile, string targetPath, Stream fileStream) => { FileInfo fi = new FileInfo(targetPath); if (!fi.Directory.Exists) fi.Directory.Create(); using var fs = File.Create(targetPath); fileStream.CopyTo(fs); nugetAssemblies.Add(targetPath); return targetPath; }, NuGet.Common.NullLogger.Instance, CancellationToken.None); resultStream.Dispose(); } return nugetAssemblies.ToArray(); } private static System.Text.RegularExpressions.Regex CreateFilter(string pattern, bool caseSensitive = false) { return new Regex("^" + Regex.Escape(pattern). Replace("\\*", ".*"). Replace("\\?", ".") + "$", caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); } private static void WriteUsage() { Console.WriteLine("\nUsage:"); Console.WriteLine(" --source=[source folder] --compareSource=[oldSourceFolder] --preprocessors=[defines] --output=[out location] --format=[html,md] --filter=[regex] --showPrivate --showInternal"); Console.WriteLine("\nRequired parameters (one or more):"); Console.WriteLine(" source Specifies the folder of source files to include for the object model.\n Separate with ; for multiple folders"); Console.WriteLine(" assemblies Specifies a set of assemblies to include for the object model.\n Separate with ; for multiple assemblies"); Console.WriteLine("\nOptional parameters:"); Console.WriteLine(" compareSource Specifies a folder to compare source and generate a diff model\n This can be useful for finding API changes or compare branches"); Console.WriteLine(" compareAssemblies Specifies a set of assemblies to include to generate a adiff model.\n Separate with ; for multiple assemblies"); Console.WriteLine(" output Output location"); Console.WriteLine(" preprocessors Define a set of preprocessors values. Use ; to separate multiple"); Console.WriteLine(" exclude Defines one or more strings that can't be part of the path Ie '/Samples/;/UnitTests/'\n (use forward slash for folder separators)"); Console.WriteLine(" regexfilter Defines a regular expression for filtering on full file names in the source"); Console.WriteLine(" referenceAssemblies Specifies a set of assemblies to include for references for better type resolution."); Console.WriteLine(" showPrivate Show private members (default is false)"); Console.WriteLine(" showInternal Show internal members (default is false)"); Console.WriteLine(" filter A set of namespaces or classes to ignore. For example: -filter=Microsoft.CSharp;Microsoft.VisualBasic"); Console.Write("Using Nuget comparison:"); Console.WriteLine(" nuget nuget packages to generate OMD for (separate multiple with semicolon). Example: /nuget=Newtonsoft.Json:13.0.0"); Console.WriteLine(" compareNuget nuget packages to compare versions with (separate multiple with semicolon). Example: /nuget=Newtonsoft.Json:12.0.0"); Console.WriteLine(" tfm Target Framework to use against NuGet package. Example: /tfm=net8.0-windows10.0.19041.0"); } } } ================================================ FILE: src/Generator/TypeExtensions.cs ================================================ using Microsoft.CodeAnalysis; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace Generator { internal static class TypeExtensions { public static string GetDescription(this ISymbol type) { string xml = null; if (type.Kind == SymbolKind.Parameter) { xml = type.ContainingSymbol.GetDocumentationCommentXml(); } else { xml = type.GetDocumentationCommentXml(); } if (!string.IsNullOrEmpty(xml)) { XmlDocument doc = new XmlDocument(); XmlElement elm = null; try { doc.LoadXml(xml); } catch { return null; } if (type.Kind == SymbolKind.Parameter) { elm = doc.GetElementsByTagName("param").OfType().Where(e => e.Attributes["name"]?.Value == type.Name).FirstOrDefault(); } else { elm = doc.GetElementsByTagName("summary").OfType().FirstOrDefault(); } if(elm != null) { foreach(var n in elm.ChildNodes.OfType()) { if(n.Name == "see") { // strip down xml to just the type name if (string.IsNullOrEmpty(n.InnerText)) { var cref = n.GetAttribute("cref"); var idx = cref.LastIndexOf("."); if (idx == -1) idx = cref.IndexOf(":"); if (idx > -1) n.InnerText = cref.Substring(idx + 1); } } } } return elm?.InnerText.Trim(); } return null; } private static IEnumerable GetAllMembers(this INamedTypeSymbol type) { IEnumerable members = type.GetMembers().Where(m => !m.IsOverride); if (!GeneratorSettings.ShowPrivateMembers) members = members.Where(m => m.DeclaredAccessibility != Accessibility.Private && m.DeclaredAccessibility != Accessibility.ProtectedAndFriend); if (!GeneratorSettings.ShowInternalMembers) members = members.Where(m => m.DeclaredAccessibility != Accessibility.Internal); return members; } internal static IEnumerable GetAllNestedTypes(this INamedTypeSymbol type) { if (type == null) return Enumerable.Empty(); IEnumerable members = type.GetTypeMembers(); if (!GeneratorSettings.ShowPrivateMembers) members = members.Where(m => m.DeclaredAccessibility != Accessibility.Private && m.DeclaredAccessibility != Accessibility.ProtectedAndFriend); if (!GeneratorSettings.ShowInternalMembers) members = members.Where(m => m.DeclaredAccessibility != Accessibility.Internal); return members; } public static IEnumerable GetMethods(this INamedTypeSymbol type) { if (type.TypeKind == TypeKind.Delegate) return Enumerable.Empty(); return type.GetAllMembers().OfType() .Where(m => m.CanBeReferencedByName) .OrderBy(m => string.Join(',', m.Parameters.Select(p => p.Name))).OrderBy(m=>m.Name); } public static IEnumerable<(IMethodSymbol symbol, bool wasRemoved, bool wasObsoleted)> GetMethods(this INamedTypeSymbol type, INamedTypeSymbol oldType) { if (oldType == null || type == null) { return GetMethods(type ?? oldType).Select(p => (p, type == null, p.IsObsolete())); //foreach (var item in GetMethods(type ?? oldType).Select(p => (p, type == null, p.IsObsolete()))) // yield return item; } else { var newMembers = GetMethods(type).ToList(); var oldMembers = GetMethods(oldType).ToList(); var result = newMembers.Except(oldMembers, Generator.MethodComparer.Comparer).Select(p => (p, false, false)) .Union(oldMembers.Except(newMembers, Generator.MethodComparer.Comparer).Select(p => (p, true, false))) .Union(newMembers.Where(n => n.IsObsolete() && oldMembers.Any(o => !o.IsObsolete() && Generator.MethodComparer.Comparer.Equals(o, n))).Select(p => (p, false, true))) //Obsoleted .OrderBy(t => string.Join(',', t.Item1.Parameters.Select(p => p.Name))).OrderBy(t => t.Item1.Name); foreach (var item in result.ToArray()) { if (item.Item2 == true)//Item was removed. Check if it was just moved up to a base-class { if (item.p.IsOverride) continue; //If override has been removed, just ignore, as it's not a removed method in that sense var basetype = type.BaseType; bool matchFound = false; while (basetype != null && !matchFound) { var members = basetype.GetMembers(item.p.Name); if (members.Any()) { var identifier = item.p.ToDisplayString(Generator.Constants.AllFormatWithoutContaining); if (members.OfType().Any(m=>identifier == m.ToDisplayString(Generator.Constants.AllFormatWithoutContaining))) { matchFound = true; continue; } } basetype = basetype.BaseType; } if (matchFound) { if (newMembers.Contains(item.p)) newMembers.Remove(item.p); else if (oldMembers.Contains(item.p)) oldMembers.Remove(item.p); continue; } //Check if optional was changed to explicit overloads if (item.p.Parameters.Any(p => p.IsOptional) && newMembers.Any(n=>n.Name == item.p.Name)) { bool found = true; var newOverloads = newMembers.Where(n => n.Name == item.p.Name).ToList(); var start = item.p.Parameters.IndexOf(item.p.Parameters.First(item => item.IsOptional)); List foundNewMembers = new List(); for (int i = start; i <= item.p.Parameters.Length; i++) { var ps = item.p.Parameters.Take(i); var matches = newOverloads.Where(n => n.Parameters.Length == i); for (int j = 0; j < i; j++) { matches = matches.Where(m => m.Parameters[j].Type.GetFullTypeName() == item.p.Parameters[j].Type.GetFullTypeName()).ToList(); } if (matches.Count() == 1) { foundNewMembers.Add(matches.Single()); } else found = false; } if (found) { foreach(var member in foundNewMembers) newMembers.Remove(member); if (oldMembers.Contains(item.p)) oldMembers.Remove(item.p); } } } } return result; } } public static IEnumerable GetProperties(this INamedTypeSymbol type) { return type.GetAllMembers().OfType().Where(m => m.CanBeReferencedByName).OrderBy(m=>m.Name); } public static IEnumerable<(IPropertySymbol symbol, bool wasRemoved, bool wasObsoleted)> GetProperties(this INamedTypeSymbol type, INamedTypeSymbol oldType) { if (oldType == null || type == null) return GetProperties(type ?? oldType).Select(p=>(p, type == null, p.IsObsolete())); var newProps = GetProperties(type); var oldProps = GetProperties(oldType); return newProps.Except(oldProps, Generator.PropertyComparer.Comparer).Select(p => (p, false, false)) .Union(oldProps.Except(newProps, Generator.PropertyComparer.Comparer).Select(p => (p, true, false))) .Union(newProps.Where(n => n.IsObsolete() && oldProps.Any(o => !o.IsObsolete() && Generator.PropertyComparer.Comparer.Equals(o, n))).Select(p => (p, false, true))) //Obsoleted .OrderBy(t => t.Item1.Name); } public static IEnumerable GetFields(this INamedTypeSymbol type) { return type.GetAllMembers().OfType().Where(m => m.CanBeReferencedByName).OrderBy(m => m.Name); } public static IEnumerable<(IFieldSymbol symbol, bool wasRemoved, bool wasObsoleted)> GetFields(this INamedTypeSymbol type, INamedTypeSymbol oldType) { if (type.TypeKind == TypeKind.Enum) return Enumerable.Empty<(IFieldSymbol symbol, bool wasRemoved, bool wasObsoleted)> (); if (oldType == null || type == null) return GetFields(type ?? oldType).Select(p => (p, type == null, p.IsObsolete())); var newProps = GetFields(type); var oldProps = GetFields(oldType); return newProps.Except(oldProps, Generator.FieldComparer.Comparer).Select(p => (p, false, false)) .Union(oldProps.Except(newProps, Generator.FieldComparer.Comparer).Select(p => (p, true, false))) .Union(newProps.Where(n => n.IsObsolete() && oldProps.Any(o => !o.IsObsolete() && Generator.FieldComparer.Comparer.Equals(o, n))).Select(p => (p, false, true))) //Obsoleted .OrderBy(t => t.Item1.Name); } public static IEnumerable GetInterfaces(this INamedTypeSymbol type) { IEnumerable i = type.Interfaces; if (!GeneratorSettings.ShowPrivateMembers) i = i.Where(m => m.DeclaredAccessibility != Accessibility.Private && m.DeclaredAccessibility != Accessibility.ProtectedAndFriend); if (!GeneratorSettings.ShowInternalMembers) i = i.Where(m => m.DeclaredAccessibility != Accessibility.Internal && m.DeclaredAccessibility != Accessibility.NotApplicable); return i; } public static IEnumerable<(INamedTypeSymbol symbol, bool wasRemoved, bool wasObsoleted)> GetInterfaces(this INamedTypeSymbol type, INamedTypeSymbol oldType) { if (oldType == null || type == null) return GetInterfaces(type ?? oldType).Select(p => (p, type == null, p.IsObsolete())); var newMembers = GetInterfaces(type); var oldMembers = GetInterfaces(oldType); return newMembers.Except(oldMembers, Generator.SymbolNameComparer.Comparer).Select(p => (p, false, false)) .Union(oldMembers.Except(newMembers, Generator.SymbolNameComparer.Comparer).Select(p => (p, true, false))) .Union(newMembers.Where(n => n.IsObsolete() && oldMembers.Any(o => !o.IsObsolete() && Generator.SymbolNameComparer.Comparer.Equals(o, n))).Select(p => (p, false, true))) //Obsoleted .OrderBy(t => t.Item1.Name); } public static bool IsSettable(this IPropertySymbol prop) { if (prop.SetMethod == null) return false; if (prop.SetMethod.DeclaredAccessibility == Accessibility.Private && !GeneratorSettings.ShowPrivateMembers) return false; if (prop.SetMethod.DeclaredAccessibility == Accessibility.Internal && !GeneratorSettings.ShowInternalMembers) return false; // if (prop.SetMethod.DeclaredAccessibility == Accessibility.Public || prop.SetMethod.DeclaredAccessibility == Accessibility.Protected) // return true; return true; } public static bool IsReadable(this IPropertySymbol prop) { if (prop.GetMethod == null) return false; if (prop.GetMethod.DeclaredAccessibility == Accessibility.Private && !GeneratorSettings.ShowPrivateMembers) return false; if (prop.GetMethod.DeclaredAccessibility == Accessibility.Internal && !GeneratorSettings.ShowInternalMembers) return false; // if (prop.SetMethod.DeclaredAccessibility == Accessibility.Public || prop.SetMethod.DeclaredAccessibility == Accessibility.Protected) // return true; return true; } public static bool IsObsolete(this ISymbol prop) { return prop.GetAttributes().Any(a => a.AttributeClass.GetFullTypeName() == "System.ObsoleteAttribute" || a.AttributeClass.GetFullTypeName() == "Obsolete"); } public static IEnumerable GetEvents(this INamedTypeSymbol type) { return type.GetAllMembers().OfType().Where(m => m.CanBeReferencedByName).OrderBy(m => m.Name); } public static IEnumerable<(IEventSymbol symbol, bool wasRemoved, bool wasObsoleted)> GetEvents(this INamedTypeSymbol type, INamedTypeSymbol oldType) { if (oldType == null || type == null) return GetEvents(type ?? oldType).Select(p => (p, type == null, p.IsObsolete())); var newMembers = GetEvents(type); var oldMembers = GetEvents(oldType); return newMembers.Except(oldMembers, Generator.EventComparer.Comparer).Select(p => (p, false, false)) .Union(oldMembers.Except(newMembers, Generator.EventComparer.Comparer).Select(p => (p, true, false))) .Union(newMembers.Where(n => n.IsObsolete() && oldMembers.Any(o => !o.IsObsolete() && Generator.EventComparer.Comparer.Equals(o, n))).Select(p => (p, false, true))) //Obsoleted .OrderBy(t => t.Item1.Name); } public static IEnumerable GetConstructors(this INamedTypeSymbol type) { if (type.TypeKind == TypeKind.Enum) return Enumerable.Empty(); IEnumerable members = type.Constructors; //.Where(c=>c.CanBeReferencedByName); if (!GeneratorSettings.ShowPrivateMembers) members = members.Where(m => m.DeclaredAccessibility != Accessibility.Private && m.DeclaredAccessibility != Accessibility.ProtectedAndFriend); if (!GeneratorSettings.ShowInternalMembers) members = members.Where(m => m.DeclaredAccessibility != Accessibility.Internal); return members.OrderBy(m => string.Join(',', m.Parameters.Select(p => p.Name))); } public static IEnumerable<(IMethodSymbol symbol, bool wasRemoved, bool wasObsoleted)> GetConstructors(this INamedTypeSymbol type, INamedTypeSymbol oldType) { if (oldType == null || type == null) return GetConstructors(type ?? oldType).Select(p => (p, type == null, p.IsObsolete())); var newMembers = GetConstructors(type).ToList(); var oldMembers = GetConstructors(oldType).ToList(); var result = newMembers.Except(oldMembers, Generator.MethodComparer.Comparer).Select(p => (p, false, false)) .Union(oldMembers.Except(newMembers, Generator.MethodComparer.Comparer).Select(p => (p, true, false))) .Union(newMembers.Where(n => n.IsObsolete() && oldMembers.Any(o => !o.IsObsolete() && Generator.MethodComparer.Comparer.Equals(o, n))).Select(p => (p, false, true))) //Obsoleted .OrderBy(t => t.Item1.Name); foreach (var item in result.ToArray()) { if (item.Item2 == true)//Item was removed. Check if it was just moved up to a base-class { //Check if optional was changed to explicit overloads if (item.p.Parameters.Any(p => p.IsOptional) && newMembers.Any(n => n.Name == item.p.Name)) { bool found = true; var newOverloads = newMembers.Where(n => n.Name == item.p.Name).ToList(); var start = item.p.Parameters.IndexOf(item.p.Parameters.First(item => item.IsOptional)); List foundNewMembers = new List(); for (int i = start; i <= item.p.Parameters.Length; i++) { var ps = item.p.Parameters.Take(i); var matches = newOverloads.Where(n => n.Parameters.Length == i); for (int j = 0; j < i; j++) { matches = matches.Where(m => m.Parameters[j].Type.GetFullTypeName() == item.p.Parameters[j].Type.GetFullTypeName()).ToList(); } if (matches.Count() == 1) { foundNewMembers.Add(matches.Single()); } else found = false; } if (found) { foreach (var member in foundNewMembers) newMembers.Remove(member); if (oldMembers.Contains(item.p)) oldMembers.Remove(item.p); } } } } return result; } public static IEnumerable GetEnums(this INamedTypeSymbol type) { if (type.TypeKind != TypeKind.Enum) return new IFieldSymbol[] { }; return type.GetAllMembers().OfType().OrderBy(f => f.ConstantValue); } public static IEnumerable<(IFieldSymbol symbol, bool wasRemoved, bool wasObsoleted)> GetEnums(this INamedTypeSymbol type, INamedTypeSymbol oldType) { if (oldType == null || type == null) return GetEnums(type ?? oldType).Select(p => (p, type == null, p.IsObsolete())); var newMembers = GetEnums(type); var oldMembers = GetEnums(oldType); return newMembers.Except(oldMembers, Generator.FieldComparer.Comparer).Select(p => (p, false, false)) .Union(oldMembers.Except(newMembers, Generator.FieldComparer.Comparer).Select(p => (p, true, false))) .Union(newMembers.Where(n => n.IsObsolete() && oldMembers.Any(o => !o.IsObsolete() && Generator.FieldComparer.Comparer.Equals(o, n))).Select(p => (p, false, true))) //Obsoleted .OrderBy(t => t.Item1.Name); } public static string GetFullTypeName(this ITypeSymbol type) { string name = type.Name; var ns = type.ContainingNamespace; while (ns != null && !ns.IsGlobalNamespace) { name = ns + "." + name; ns = ns.ContainingNamespace; } return name; } public static string GetFullNamespace(this ITypeSymbol type) { var name = ""; var ns = type.ContainingNamespace; while (ns != null && !ns.IsGlobalNamespace) { if (string.IsNullOrEmpty(name)) name += ns.Name; else name = ns.Name + "." + name; ns = ns.ContainingNamespace; } return name; } public static string GetFullTypeString(this INamedTypeSymbol type) { string result = type.Name; if (type.TypeArguments.Length > 0) { result += "<"; bool isFirstIteration = true; foreach (INamedTypeSymbol typeArg in type.TypeArguments.OfType< INamedTypeSymbol>()) { if (isFirstIteration) { isFirstIteration = false; } else { result += ", "; } result += GetFullTypeString(typeArg); } result += ">"; } return result; } public static string GetFullNamespace(this INamespaceSymbol ns) { if (ns.IsGlobalNamespace) return string.Empty; string name = ns.Name; ns = ns.ContainingNamespace; while (ns != null && !ns.IsGlobalNamespace) { name = ns + "." + name; ns = ns.ContainingNamespace; } return name; } } } ================================================ FILE: src/Generator/WorkspaceHelper.cs ================================================ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Generator { internal class Generator { private IEnumerable generators; public Generator(IEnumerable generators) { this.generators = generators; } internal async Task Process(IEnumerable paths, IEnumerable assemblies, IEnumerable preprocessors = null, Regex[] filters = null, string[] referenceAssemblies = null, string[] objectFilters = null) { var compilation = await CreateCompilationAsync(paths, assemblies, preprocessors, filters, referenceAssemblies); Console.WriteLine("Processing types..."); var symbols = GetSymbols(compilation.compilation, compilation.metadata); foreach (var generator in generators) { generator.Initialize(symbols); foreach (var s in symbols) { if (objectFilters is not null && objectFilters.Any(o => s.ToDisplayString().StartsWith(o))) continue; GenerateCode(generator, s); } generator.Complete(); } Console.WriteLine("Complete"); } private List GetSymbols(Compilation compilation, IEnumerable assemblies) { Action> getNamespaces = null; getNamespaces = (inss, list) => { foreach (var childNs in inss.GetMembers().OfType().Where(n => n.Locations.Any(l => l.Kind == LocationKind.SourceFile))) { list.Add(childNs); getNamespaces(childNs, list); } foreach (var childNs in inss.GetMembers().OfType().Where(n => n.Locations.Any(l => l.Kind == LocationKind.MetadataFile))) { list.Add(childNs); getNamespaces(childNs, list); } }; List namespaces = new List(); getNamespaces(compilation.GlobalNamespace, namespaces); List symbols = new List(); foreach (var ns in namespaces) { symbols.AddRange(GetTypes(ns, assemblies)); } symbols = symbols.OrderBy(t => t.Name).OrderBy(t => t.GetFullNamespace()).ToList(); return symbols; } private IEnumerable GetTypes(INamespaceSymbol ns, IEnumerable assemblies) { foreach (var type in ns.GetTypeMembers().OfType()) { if (type.Locations.Any(l => l.Kind == LocationKind.MetadataFile)) { var loc = type.Locations.First(l => l.Kind == LocationKind.MetadataFile); var meta = loc.MetadataModule.GetMetadata(); if (!assemblies.Any(n => n.Display.EndsWith(meta.Name))) continue; } else if (type.Locations.Any(l => l.Kind != LocationKind.SourceFile)) continue; if (type.DeclaredAccessibility == Accessibility.Private && !GeneratorSettings.ShowPrivateMembers) continue; if (type.DeclaredAccessibility == Accessibility.Internal && !GeneratorSettings.ShowInternalMembers) continue; yield return type; } } private void GenerateCode(ICodeGenerator generator, INamedTypeSymbol type) { Console.WriteLine(type.GetFullTypeName()); if (type.TypeKind == TypeKind.Enum) generator.WriteEnum(type); else if (type.TypeKind == TypeKind.Interface) generator.WriteInterface(type); else if (type.TypeKind == TypeKind.Class || type.TypeKind == TypeKind.Struct) generator.WriteClass(type); else if (type.TypeKind == TypeKind.Delegate) generator.WriteDelegate(type); else { Console.WriteLine("****TODO**** ERROR: No generator for type " + type.GetFullTypeName() + " of kind " + type.TypeKind.ToString()); } } internal async Task<(Compilation compilation, List metadata)> CreateCompilationAsync(IEnumerable paths, IEnumerable assemblies, IEnumerable preprocessors = null, Regex[] filters = null, string[] referenceAssemblies = null) { Console.WriteLine("Creating workspace..."); var ws = new AdhocWorkspace(); var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default); ws.AddSolution(solutionInfo); var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "CSharpExample", "CSharpExample", "C#"); ws.AddProject(projectInfo); if (paths != null) { foreach (var path in paths) { if (path.StartsWith("http://") || path.StartsWith("https://")) { await DownloadDocumentsAsync(path, ws, projectInfo.Id, filters).ConfigureAwait(false); } else if (path.EndsWith(".zip")) { LoadCompressedDocuments(path, ws, projectInfo.Id, filters); } else { LoadFolderDocuments(path, ws, projectInfo.Id, filters); } } } Console.WriteLine("Compiling..."); var project = ws.CurrentSolution.Projects.Single(); List metadata = new List(); if (assemblies != null) { foreach (var assm in assemblies) { IEnumerable files = Enumerable.Empty(); if (File.Exists(assm)) { files = new FileInfo[] { new FileInfo(assm) }; } else { string recursive = Path.DirectorySeparatorChar + "**" + Path.DirectorySeparatorChar; bool isRecursive = false; var d = assm; var fn = Path.GetFileName(assm); if (d.Contains(recursive)) { d = d.Substring(0, d.IndexOf(recursive)); isRecursive = true; } else if (Directory.Exists(d)) { fn = null; } else { d = Path.GetDirectoryName(d); } var dir = new DirectoryInfo(d); if (!dir.Exists) throw new DirectoryNotFoundException(d); if (string.IsNullOrEmpty(fn)) { files = dir.GetFiles("*.dll", isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); } else { var di = new DirectoryInfo(d); files = dir.GetFiles(fn, isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); } } foreach (var item in files) { var metaref = MetadataReference.CreateFromFile(item.FullName); project = project.AddMetadataReference(metaref); metadata.Add(metaref); } } } if (referenceAssemblies != null) { foreach (var refasm in referenceAssemblies) { if (File.Exists(refasm)) { project = project.WithParseOptions(new Microsoft.CodeAnalysis.CSharp.CSharpParseOptions(Microsoft.CodeAnalysis.CSharp.LanguageVersion.Latest, DocumentationMode.Parse, SourceCodeKind.Regular, preprocessors)); var metaref = MetadataReference.CreateFromFile(refasm); project = project.AddMetadataReference(metaref); } } } var comp = await project.GetCompilationAsync().ConfigureAwait(false); return (comp, metadata); } private async Task DownloadDocumentsAsync(string uri, AdhocWorkspace ws, ProjectId projectId, Regex[] filters) { var handler = new HttpClientHandler() { AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate }; var client = new HttpClient(handler); HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get, uri); msg.Headers.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("DotNetOMDGenerator", "1.0")); Console.WriteLine("Downloading " + uri + "..."); using (var result = await client.SendAsync(msg, HttpCompletionOption.ResponseHeadersRead)) { var content = result.EnsureSuccessStatusCode().Content; using (var s = await content.ReadAsStreamAsync()) { var headers = result.Headers.ToArray(); var filename = Path.GetTempFileName(); var name = content.Headers.ContentDisposition?.FileName; if (content.Headers.ContentType?.MediaType == "application/zip") { var length = content.Headers.ContentLength; using (var f = System.IO.File.OpenWrite(filename)) { var buffer = new byte[65536]; long read = 0; int count = -1; while (count != 0) { count = await s.ReadAsync(buffer, 0, buffer.Length); if (count > 0) await f.WriteAsync(buffer, 0, count); read += count; if (length.HasValue) Console.Write($" \r{(read * 100.0 / length.Value).ToString("0.0")}% ({(length.Value / 1024d / 1024d).ToString("0.0")}mb)"); else Console.Write($" \r{read} bytes..."); } Console.WriteLine(); } LoadCompressedDocuments(filename, ws, projectId, filters); File.Delete(filename); } else if (content.Headers.ContentType?.MediaType == "text/plain") { var sourceText = SourceText.From(s); ws.AddDocument(projectId, name ?? "Unknown.cs", sourceText); } else throw new Exception("Invalid or missing content type: " + content.Headers.ContentType?.MediaType); } } } private void LoadCompressedDocuments(string zipFile, AdhocWorkspace ws, ProjectId projectId, Regex[] filters) { using (var s = File.OpenRead(zipFile)) { System.IO.Compression.ZipArchive a = new System.IO.Compression.ZipArchive(s, System.IO.Compression.ZipArchiveMode.Read); foreach (var e in a.Entries) { if (string.IsNullOrEmpty(e.Name)) //Folder continue; var fullname = e.FullName.Replace('\\', '/'); if (filters == null || !filters.Where(f => f.IsMatch(fullname)).Any()) { if (e.Name.EndsWith(".cs")) { using (var sr = new StreamReader(e.Open())) { var sourceText = SourceText.From(sr.ReadToEnd()); ws.AddDocument(projectId, e.Name, sourceText); } } } } } } private void LoadFolderDocuments(string pathName, AdhocWorkspace ws, ProjectId projectId, Regex[] filters) { FileInfo f = new FileInfo(pathName); DirectoryInfo di = null; IEnumerable files; if (f.Exists) { files = new FileInfo[] { f }; } else { di = new DirectoryInfo(pathName); files = di.GetFiles("*.cs"); if (filters != null) files = files.Where(n => !filters.Where(fl => fl.IsMatch(n.FullName.Replace('\\', '/'))).Any()); } foreach (var file in files) { var sourceText = SourceText.From(File.OpenRead(file.FullName)); ws.AddDocument(projectId, file.Name, sourceText); } if (di != null) { foreach (var dir in di.GetDirectories()) { LoadFolderDocuments(dir.FullName, ws, projectId, filters); } } } //************* Difference comparisons *******************/ internal async Task ProcessDiffs(string[] oldPaths, string[] newPaths, IEnumerable oldAssemblies, IEnumerable newAssemblies, IEnumerable preprocessors = null, Regex[] filters = null, string[] referenceAssemblies = null, string[] objectFilters = null) { var oldCompilation = await CreateCompilationAsync(oldPaths, oldAssemblies, preprocessors, filters, referenceAssemblies); var newCompilation = await CreateCompilationAsync(newPaths, newAssemblies, preprocessors, filters, referenceAssemblies); var oldSymbols = GetSymbols(oldCompilation.compilation, oldCompilation.metadata); var newSymbols = GetSymbols(newCompilation.compilation, newCompilation.metadata); var symbols = GetChangedSymbols(newSymbols, oldSymbols); int i = 0; foreach (var generator in generators.OfType()) { generator.Initialize(newSymbols, oldSymbols); i = 0; foreach (var s in symbols) { if (objectFilters is not null && objectFilters.Any(o => s.oldSymbol != null && s.oldSymbol.ToDisplayString().StartsWith(o) || s.newSymbol != null && s.newSymbol.ToDisplayString().StartsWith(o))) continue; GenerateCode(generator, s.newSymbol, s.oldSymbol); i++; } generator.Complete(); } Console.WriteLine($"Complete. {i} symbols with changes found"); } internal static IEnumerable<(INamedTypeSymbol newSymbol, INamedTypeSymbol oldSymbol)> GetChangedSymbols(IEnumerable newSymbols, IEnumerable oldSymbols) { var symbolNameComparer = new SymbolNameComparer(); var removedSymbols = oldSymbols.Except(newSymbols, symbolNameComparer).ToList(); //Objects that have been removed var addedSymbols = newSymbols.Except(oldSymbols, symbolNameComparer).ToList(); //Objects that have been added var sameNewSymbols = newSymbols.Intersect(oldSymbols, symbolNameComparer).ToList(); // Objects present before and after var sameOldSymbols = oldSymbols.Intersect(newSymbols, symbolNameComparer).ToList(); // Objects present before and after var changedSymbols = sameNewSymbols.Except(sameOldSymbols, new SymbolMemberComparer()) .Union(sameNewSymbols.Where(n=>n.IsObsolete() && !sameOldSymbols.Single(o=>symbolNameComparer.Equals(n, o)).IsObsolete())) .ToList(); //Objects that have changes List<(INamedTypeSymbol newSymbol, INamedTypeSymbol oldSymbol)> symbols = new List<(INamedTypeSymbol newSymbol, INamedTypeSymbol oldSymbol)>(); foreach (var s in addedSymbols) symbols.Add((s, null)); foreach (var s in removedSymbols) symbols.Add((null, s)); foreach (var s in changedSymbols) { var name = s.GetFullTypeName(); var oldS = oldSymbols.Where(o => o.GetFullTypeName() == name).First(); symbols.Add((s, oldS)); } return symbols.OrderBy(s => (s.Item1 ?? s.Item2).Name).OrderBy(s => (s.Item1 ?? s.Item2).GetFullNamespace()).ToList(); } private void GenerateCode(ICodeDiffGenerator generator, INamedTypeSymbol type, INamedTypeSymbol oldType) { if (type == null && oldType == null) throw new ArgumentNullException("Both old and new type can't be null"); var t = (type ?? oldType); Console.WriteLine(t.GetFullTypeName()); if (t.TypeKind == TypeKind.Enum) generator.WriteEnum(type, oldType); else if (t.TypeKind == TypeKind.Interface) generator.WriteInterface(type, oldType); else if (t.TypeKind == TypeKind.Class || t.TypeKind == TypeKind.Struct) generator.WriteClass(type, oldType); else if (t.TypeKind == TypeKind.Delegate) generator.WriteDelegate(type, oldType); else { Console.WriteLine("****TODO**** ERROR: No generator for type " + t.GetFullTypeName() + " of kind " + t.TypeKind.ToString()); } } internal class SymbolNameComparer : IEqualityComparer { internal static SymbolNameComparer Comparer = new SymbolNameComparer(); public bool Equals(INamedTypeSymbol x, INamedTypeSymbol y) => x.ToDisplayString().Equals(y.ToDisplayString()); public int GetHashCode(INamedTypeSymbol obj) => obj.ToDisplayString().GetHashCode(); } private class SymbolMemberComparer : IEqualityComparer { public bool Equals(INamedTypeSymbol x, INamedTypeSymbol y) { //TODO: Also check base types. It's ok to move members up the hiarchy if (x.BaseType?.ToDisplayString() != y.BaseType?.ToDisplayString()) return false; // Inheritance changed if (x.TypeKind != y.TypeKind) return false; var ifacesNew = x.GetInterfaces(); var ifacesOld = y.GetInterfaces(); if (ifacesNew.Count() != ifacesOld.Count()) return false; if (x.TypeKind == TypeKind.Enum && x.EnumUnderlyingType?.ToDisplayString() != y.EnumUnderlyingType?.ToDisplayString()) return false; //Enum type changed // Compare member count var constructorsNew = x.GetConstructors(); var constructorsOld = y.GetConstructors(); if (constructorsNew.Count() != constructorsOld.Count()) return false; var propsNew = x.GetProperties(); var propsOld = y.GetProperties(); if (propsNew.Count() != propsOld.Count()) return false; var methodsNew = x.GetMethods(); var methodsOld = y.GetMethods(); if (methodsNew.Count() != methodsOld.Count()) return false; var eventsNew = x.GetEvents(); var eventsOld = y.GetEvents(); if (eventsNew.Count() != eventsOld.Count()) return false; var fieldsNew = x.GetEnums(); var fieldsOld = y.GetEnums(); if (fieldsNew.Count() != fieldsOld.Count()) return false; if (ifacesNew.Except(ifacesOld, SymbolNameComparer.Comparer).Any() || ifacesOld.Except(ifacesNew, SymbolNameComparer.Comparer).Any()) return false; if (propsNew.Except(propsOld, PropertyComparer.Comparer).Any() || propsOld.Except(propsNew, PropertyComparer.Comparer).Any()) return false; if (constructorsNew.Except(constructorsOld, MethodComparer.Comparer).Any() || constructorsOld.Except(constructorsNew, MethodComparer.Comparer).Any()) return false; if (propsNew.Except(propsOld, PropertyComparer.Comparer).Any() || propsOld.Except(propsNew, PropertyComparer.Comparer).Any()) return false; if (methodsNew.Except(methodsOld, MethodComparer.Comparer).Any() || methodsOld.Except(methodsNew, MethodComparer.Comparer).Any()) return false; if (eventsNew.Except(eventsOld, EventComparer.Comparer).Any() || eventsOld.Except(eventsNew, EventComparer.Comparer).Any()) return false; if (fieldsNew.Except(fieldsOld, FieldComparer.Comparer).Any() || fieldsOld.Except(fieldsNew, FieldComparer.Comparer).Any()) return false; return true; } public int GetHashCode(INamedTypeSymbol obj) => obj.GetFullTypeName().GetHashCode(); } internal static class Constants { public static readonly SymbolDisplayFormat AllFormat = new SymbolDisplayFormat( SymbolDisplayGlobalNamespaceStyle.Included, SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, (SymbolDisplayGenericsOptions)255, (SymbolDisplayMemberOptions)255, (SymbolDisplayDelegateStyle)255, (SymbolDisplayExtensionMethodStyle)255, (SymbolDisplayParameterOptions)255, SymbolDisplayPropertyStyle.NameOnly, (SymbolDisplayLocalOptions)255, (SymbolDisplayKindOptions)255, (SymbolDisplayMiscellaneousOptions)255); public static readonly SymbolDisplayFormat AllFormatWithoutContaining = new SymbolDisplayFormat( SymbolDisplayGlobalNamespaceStyle.Omitted, SymbolDisplayTypeQualificationStyle.NameOnly, (SymbolDisplayGenericsOptions)255, (SymbolDisplayMemberOptions)223, (SymbolDisplayDelegateStyle)255, (SymbolDisplayExtensionMethodStyle)255, (SymbolDisplayParameterOptions)255, SymbolDisplayPropertyStyle.NameOnly, (SymbolDisplayLocalOptions)255, (SymbolDisplayKindOptions)255, (SymbolDisplayMiscellaneousOptions)255); } internal class PropertyComparer : IEqualityComparer { internal static PropertyComparer Comparer = new PropertyComparer(); public bool Equals(IPropertySymbol x, IPropertySymbol y) { if (!x.ToDisplayString(Constants.AllFormat).Equals(y.ToDisplayString(Constants.AllFormat))) return false; IMethodSymbol gx = (x.GetMethod?.DeclaredAccessibility == Accessibility.Public || (x.GetMethod?.DeclaredAccessibility == Accessibility.Internal && GeneratorSettings.ShowInternalMembers) || (x.GetMethod?.DeclaredAccessibility == Accessibility.Private && GeneratorSettings.ShowPrivateMembers)) ? x.GetMethod : null; IMethodSymbol gy = (y.GetMethod?.DeclaredAccessibility == Accessibility.Public || (y.GetMethod?.DeclaredAccessibility == Accessibility.Internal && GeneratorSettings.ShowInternalMembers) || (y.GetMethod?.DeclaredAccessibility == Accessibility.Private && GeneratorSettings.ShowPrivateMembers)) ? y.GetMethod : null; if (gx?.DeclaredAccessibility != gy?.DeclaredAccessibility) return false; IMethodSymbol sx = (x.SetMethod?.DeclaredAccessibility == Accessibility.Public || (x.SetMethod?.DeclaredAccessibility == Accessibility.Internal && GeneratorSettings.ShowInternalMembers) || (x.SetMethod?.DeclaredAccessibility == Accessibility.Private && GeneratorSettings.ShowPrivateMembers)) ? x.SetMethod : null; IMethodSymbol sy = (y.SetMethod?.DeclaredAccessibility == Accessibility.Public || (y.SetMethod?.DeclaredAccessibility == Accessibility.Internal && GeneratorSettings.ShowInternalMembers) || (y.SetMethod?.DeclaredAccessibility == Accessibility.Private && GeneratorSettings.ShowPrivateMembers)) ? y.SetMethod : null; if (sx?.DeclaredAccessibility != sy?.DeclaredAccessibility) return false; return true; } public int GetHashCode(IPropertySymbol obj) => obj.ToDisplayString(Constants.AllFormat).GetHashCode(); } internal class MethodComparer : IEqualityComparer { public static MethodComparer Comparer = new MethodComparer(); public bool Equals(IMethodSymbol x, IMethodSymbol y) => x.ToDisplayString(Constants.AllFormat).Equals(y.ToDisplayString(Constants.AllFormat)); public int GetHashCode(IMethodSymbol obj) => obj.ToDisplayString(Constants.AllFormat).GetHashCode(); } internal class EventComparer : IEqualityComparer { public static EventComparer Comparer = new EventComparer(); public bool Equals(IEventSymbol x, IEventSymbol y) => x.ToDisplayString(Constants.AllFormat).Equals(y.ToDisplayString(Constants.AllFormat)); public int GetHashCode(IEventSymbol obj) => obj.ToDisplayString(Constants.AllFormat).GetHashCode(); } internal class FieldComparer : IEqualityComparer { public static FieldComparer Comparer = new FieldComparer(); public bool Equals(IFieldSymbol x, IFieldSymbol y) => FormatField(x).Equals(FormatField(y)); public int GetHashCode(IFieldSymbol obj) => obj.ToDisplayString(Constants.AllFormat).GetHashCode(); private static string FormatField(IFieldSymbol x) { return x.ToDisplayString(Constants.AllFormat) + "=" + x.ConstantValue?.ToString(); } } } } ================================================ FILE: src/Generator/dotMorten.OmdGenerator.targets ================================================ $(MSBuildThisFileDirectory)..\tools\netcoreapp2.1\any\generateomd.dll html ================================================ FILE: src/Generator.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.27130.2027 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Generator", "Generator\Generator.csproj", "{AD341C4A-21E0-4268-B573-5C37A727BC23}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{5BC4D75B-15DF-4FA8-9981-2021ACED5AFD}" ProjectSection(SolutionItems) = preProject ..\README.md = ..\README.md EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {AD341C4A-21E0-4268-B573-5C37A727BC23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AD341C4A-21E0-4268-B573-5C37A727BC23}.Debug|Any CPU.Build.0 = Debug|Any CPU {AD341C4A-21E0-4268-B573-5C37A727BC23}.Release|Any CPU.ActiveCfg = Release|Any CPU {AD341C4A-21E0-4268-B573-5C37A727BC23}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {1449C758-CD7D-4A6A-AA3D-B7F9B0A4764E} EndGlobalSection EndGlobal