Christian Schou
  • Home
  • Blog
    • Programming
      • C#
      • PowerShell
      • Python
      • SQL
    • WordPress
      • Tutorials
    • Cloud
    • Home Automation
      • Home Assistant
        • Node-Red
    • Career
  • Services
  • Glossary
  • About
No Result
View All Result
Christian Schou
  • Home
  • Blog
    • Programming
      • C#
      • PowerShell
      • Python
      • SQL
    • WordPress
      • Tutorials
    • Cloud
    • Home Automation
      • Home Assistant
        • Node-Red
    • Career
  • Services
  • Glossary
  • About
No Result
View All Result
Christian Schou
No Result
View All Result
Home Programming
docfx

How to produce documentation from source code with DocFX in .NET Core solutions

by Christian
27. Dezember 2021
in Programming
3

I recently made a big project in a company that is responsible for handling all shipment data between the internal ERP and the carriers. During this project, I needed to generate documentation for the API I had developed.

During my time as a developer I have been working with several tools to help with the (boring) documentation part and I have finally chosen a tool – DocFX. Why is that Christian? Well, I primarily write code in Microsoft Languages (C#, etc…) and behind the scenes, Microsoft makes use of DocFX to generate its documentation. Due to that it makes really good sense for me to use the same tool as the documentation I often make is similar to the type of documentation often consume.

If you are ready, then let’s get started with DocFX and make some documentation for your .NET Core application.

Inhaltsverzeichnis
  1. What is DocFX?
  2. Visual Studio Code Extensions making documentation easier
  3. Getting started with DocFX
    • Integrate DocFX into Visual Studio
  4. Creating Documentation with DocFX
    • Folder structure
      • _site
      • api
      • articles
      • root folder
    • How to configure DocFX
      • Metadata
      • Build
      • Template
    • Host your documentation locally (on the dev machine)
    • How to customize your documentation website
      • Add another section to your navigation menu bar
  5. DocFx Templates
  6. Including diagrams in your documentation (Mermaid with DocFX)
  7. Summary

What is DocFX?

To make it short and move on to the crucial part of this tutorial I will only give a short introduction to what DocFX is. DocFX is a command-line tool that is capable of producing a static website containing documentation for your application. It can use both Markdown files as well as your source code to generate the documentation. DocFX is a highly customizable tool that allows you to even modify the theme using templates and is possible to run in almost any environment. As you might have noticed – the generated website is static and can be deployed for a very low price on several Cloud Providers hosting plans.

Visual Studio Code Extensions making documentation easier

Below is a shortlist that references some of my favorite tools when talking documentation. They will help you in the development of the markdown that DocFX uses when it’s generating the documentation website.

  • YAML by Red Hat – Provides comprehensive YAML Language support to Visual Studio Code, via the yaml-language-server, with built-in Kubernetes syntax support.
  • docs-article-templates by Microsoft – The Docs Article Templates extension lets writers in VS Code pull a Markdown template from a centralized store and apply it to a file.
  • Markdown All in One by Yu Zhang – All you need for Markdown (keyboard shortcuts, table of contents, auto preview and more).
  • markdownlint by David Anson – markdownlint is a Visual Studio Code extension that includes a library of rules to encourage standards and consistency for Markdown files.

Getting started with DocFX

You got multiple options when it comes to the way you want to use DocFX. If you are going for the command line, then you have to visit the GitHub repo releases for DocFX. At the repo, you will be able to download the latest stable release as well as beta releases. I always go for stable releases unless it’s a test project.

A second option for the command line is to use the Chocolately DocFX Package. You can install the package using the following command: choco install docfx -y. “-y” is for accepting terms when installing, else you will be prompted for that during installation.

The last option and the one I tend to use the most is through NuGet, where you can install DocFX directly from within your console in the IDE. The command to install DocFX using NuGet installer is: nuget install docfx.console. If you are doing it from the NuGet Console, you can use the following command: Install-Package docfx.console.

Integrate DocFX into Visual Studio

If you like me would like to have DocFX integrated directly inside Visual Studio, you can easily accomplish this too. The only thing you have to do is add a new class library to your existing solution and add the docfx.console NuGet package to the newly created library. The first time you build your application after the above has been added, the library will automatically generate the content for the static website.

Creating Documentation with DocFX

In the rest of this tutorial, I will be using the built-in DocFX inside Visual Studio. Now let’s move on to the part where the magic happens – the generation of the static documentation.

Folder structure

To get an understanding of how the content is organized I thought it would be a good idea, to include a description of the default folder structure that will be generated upon the first build of your application. Below the image is a short description of what is inside the folders.

default docfx folder structure
Default folder structure

_site

_site contains static assets/files that have been generated by the package and are the content that you should be uploading to your host. In other words – it’s the static website showing off your documentation.

api

Iside the api folder, you will find all your documentation files, generated by the package.

articles

If you decide to manually write documentation in Markdown, you have to place them inside the articles folder.

root folder

  • docfx.json – Is used to configure how the package generates the documentaion upon build as well as what it is generating the documentation for.
  • index.md – The name says it all. This page is the landing page for your documentation website.
  • toc.yml – This file is used to populate the navigation header of your documentation website.

How to configure DocFX

The JSON file named docfx.json is the one containing all information that DocFX needs in order to compile the documentation source into a static website that you can populate. Below is a list of properties you can adjust to your needs. This is one part that makes this tool very flexible when it comes to configuration.

Metadata

"metadata": [
    {
      "src": [
        {
          "files": [
            "**.csproj"
          ],
          "src": "C:\\Users\\Christian Schou\\source\\repos\\DocFxAPI\\DocFX"
        }
      ],
      "dest": "api",
      "disableGitFeatures": false,
      "disableDefaultFilter": false
    }
  ]

This property lists the source directory, source files, and API directory.

Build

"build": {
    "content": [
      {
        "files": [
          "api/**.yml",
          "api/index.md"
        ]
      },
      {
        "files": [
          "articles/**.md",
          "articles/**/toc.yml",
          "toc.yml",
          "*.md"
        ]
      }
    ],
    "resource": [
      {
        "files": [
          "images/**"
        ]
      }
    ],
    "overwrite": [
      {
        "files": [
          "apidoc/**.md"
        ],
        "exclude": [
          "obj/**",
          "_site/**"
        ]
      }
    ]

This property instructs DocFX about the type of files we expect to be building. It also includes details about where the resource files will be located, what files are allowed to be overwritten upon build, and if we should exclude something from the documentation.

Template

"template": [
      "default"
    ]

When using the template property, we can extend the documentation website with a template we would like. If you list “default” as the first template, you can allow other templates to inherit. This makes up for a good way to only extend the areas we would like.

Host your documentation locally (on the dev machine)

Now that the site has been built for our project, we can open a terminal or command-line interface and navigate to the folder where our documentation website is hosted. Let’s launch the website using the following command: docfx docfx.json serve. This command will serve your site locally on the development machine and allow for the developer (you) to review any changes before they would be deployed to the populated documentation website.

Serve documentation website from CMD

This is the site hosted on the just populated port 8080.

docfx
Default Landing Page

How to customize your documentation website

Notice for those who run the site locally

If you are running the documentation website locally, you have to stop serving the website, rebuild the solution, serve the website again as we did above, and do a hard refresh in your browser (shift + F5) to see the new changes you just made.

Add another section to your navigation menu bar

Now go back to your class library in Visual Studio and open up toc.yml. This file is the one holding details about contents on your website. You can see this one as a table of contents file. In order to add a new section, all you have to do is add the following:

  • Use the name parameter, this will identify the section by a name.
  • Use the href parameter to specify where the documentation for that specific section is located.
  • Use the topicHref parameter to link to a specific file inside the href folder.

DocFx Templates

By default, DocFX has some pre-defined templates that you can choose between. You can visit this page to see Templates & Plugins you can use on your website. On each template page, you can see the command you need to add inside your docfx.json file to use the template.

Below is an example of how to use the Material template. Please notice that I have created a folder named templates and places the material template inside that one.

"template": [
      "default",
      "templates/material"
    ]
DocFX Material
DocFX with Material Template

Including diagrams in your documentation (Mermaid with DocFX)

A short introduction… Mermaid is a JavaScript tool that allows you to render diagrams and charts dynamically from your written markdown. How cool is that? Often when documenting applications, we can write tons of pages of how the application is structured, how calls are received and returned, how the application stack is made up, etc…

Using Mermaid we can add support for several diagrams that are often used when documenting code. This includes diagrams like:

  • Flow Chart
  • Sequence Diagram
  • Class Diagram
  • State Diagram
  • Etc…

Below is an example of a very simple sequence diagram showing a conversation between Alice and John. If you want some examples of sequence diagram markdown for testing purposes, you can check this repo: mermaid-js blobs. The markdown to generate the image below, is the one I have added below:

```mermaid
sequenceDiagram
    participant Alice
    participant John

    rect rgb(191, 223, 255)
    note right of Alice: Alice calls John.
    Alice->>+John: Hello John, how are you?
    rect rgb(200, 150, 255)
    Alice->>+John: John, can you hear me?
    John-->>-Alice: Hi Alice, I can hear you!
    end
    John-->>-Alice: I feel great!
    end
    Alice ->>+ John: Did you want to go to the game tonight?
    John -->>- Alice: Yeah! See you there.
```

Out of the box, Mermaid is unfortunately not supported, but luckily we can easily add it to our solution. To use Mermaid inside your website, we will extend our default template with a partial.

To add a partial file to the default theme, all you have to do is add a folder in the templates named mermaid. Inside that folder you have to add a new subfolder named partials and add a new file named: scripts.tmpl.partial. See the structure below for reference:

Add partials to default DocFX template

Now add the following line of codes to that newly created file scripts.tmpl.partial.

<script type="text/javascript" src="{{_rel}}styles/docfx.vendor.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/highlight.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/dotnetconfig.min.js"></script>
<script type="text/javascript" src="{{_rel}}styles/docfx.js"></script>
<script type="text/javascript" src="{{_rel}}styles/main.js"></script>
<script type="text/javascript" src="https://unpkg.com/[email protected]/dist/mermaid.min.js"
integrity="sha384-nzpOk138h0/O14Ig1PAUlf1XSo5T+XvpBUVkpLaU40QBvMgrNkSKusdNAomDLEd2"
crossorigin="anonymous"></script>
<script>
mermaid.initialize({
startOnLoad: false
});
mermaid.init(undefined, ".lang-mermaid");
</script>

That’s it! Now go to an article page and add a sample sequence diagram and serve your website again. The diagram should now be rendered as an image instead of the text you wrote in the markdown.

Summary

If you are a software developer who is currently using the Microsoft Technology Stack and you would like to make meaningful documentation in a nice and easy way, then DocFX might be the choice for you. I use it a lot and everyone who is reading my documentation always says that it’s awesome to read so well-documented solutions.

It can be integrated into your CI/CD pipeline and can be automatically populated upon new releases. Can it be easier!? In the future, I hope that the guys behind DocFX will be adding support for OpenAPI 3.0 documents, as that would allow us to automatically add documentation generated by Swagger (a nice API tool).

If you got any issues, questions, or suggestions, please let me know in the comments. Happy coding! 🙂

Tags: .Net CoreAPIASP.NET CoreC#CLIDevelopmentDocFXDocumentationWeb
Previous Post

How to visualize .NET Core API usage with Prometheus and Grafana

Next Post

How to add localization in ASP.NET Core Web APIs with Caching

Christian

Christian

Hello 👋 My name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Related Posts

watchdog
ASP.NET Core

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

by Christian
13. August 2022
0

A reader recently asked me for a more modern way to view log files for requests and exceptions in a...

Read more
restful web api

How to build a RESTful Web API using ASP.NET Core and Entity Framework Core (.NET 6)

25. Juli 2022
dynamically register entities

How to Dynamically Register Entities in DbContext by Extending ModelBuilder?

23. Juli 2022
Dockerize ASP.NET Core

How to Compose an ASP.NET Core Web API (.NET 6) with an MS SQL Server 2022 on Linux in Docker

19. Juli 2022
sql views

SQL Views – A Complete 101 guide to work with SQL Views

7. August 2022
Next Post
localization in ASP.NET Core Web API

How to add localization in ASP.NET Core Web APIs with Caching

Comments 3

  1. Zenaida Carrillo says:
    6 Monaten ago

    Thanks for thе marvelous posting! I seriously enjoyed reading іt, you’rе a ցreat author. I will ensure that I bookmark уour blog and may cоmе baϲk dⲟwn the road. Ӏ want to encourage you tⲟ ԁefinitely continue your gгeat job, have a nice evening!

    Antworten
    • Christian Schou says:
      5 Monaten ago

      Hi Zenaida

      Thank you for stopping by and taking your time to write that comment. Have a great evening too! 🙂

      Antworten
  2. Jack Scheurmann says:
    2 Monaten ago

    This is very interesting, You’re a very skilled blogger. I have joined your RSS feed and look forward to seeking more of your fantastic post. Also, I’ve shared your website in my social networks!

    Antworten

Schreibe einen Kommentar Antworten abbrechen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Christian Schou

Christian Schou

Software Developer

Hello - my name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Recent articles

personal website
Career

Top 6 things to add on your personal website to get hired for a tech job

by Christian
7. August 2022
0

Back in the days before the internet was a thing like it is today, we used to have business cards...

Read more
watchdog

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

13. August 2022
get hired for a tech job

5 tips to help you get hired for a tech job

31. Juli 2022
restful web api

How to build a RESTful Web API using ASP.NET Core and Entity Framework Core (.NET 6)

25. Juli 2022
dynamically register entities

How to Dynamically Register Entities in DbContext by Extending ModelBuilder?

23. Juli 2022

Christian Schou

Software Developer

Hello - my name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Recent articles

personal website

Top 6 things to add on your personal website to get hired for a tech job

7. August 2022
watchdog

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

13. August 2022
get hired for a tech job

5 tips to help you get hired for a tech job

31. Juli 2022
  • de_DEDeutsch
    • da_DKDansk
    • en_USEnglish
    • hi_INहिन्दी
    • pt_BRPortuguês do Brasil
  • Contact
  • Datenschutzrichtlinie
  • Nutzungsbedingungen

© 2022 Christian Schou - All rights reserved.

No Result
View All Result
  • Home
  • Blog
    • Programming
      • C#
      • PowerShell
      • Python
      • SQL
    • WordPress
      • Tutorials
    • Cloud
    • Home Automation
      • Home Assistant
    • Career
  • Services
  • Glossary
  • About

© 2022 Christian Schou - All rights reserved.

I use cookies on my website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie settingsACCEPT
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
immer aktiv
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
CookieDauerBeschreibung
__gads1 year 24 daysThe __gads cookie, set by Google, is stored under DoubleClick domain and tracks the number of times users see an advert, measures the success of the campaign and calculates its revenue. This cookie can only be read from the domain they are set on and will not track any data while browsing through other sites.
_ga2 yearsThe _ga cookie, installed by Google Analytics, calculates visitor, session and campaign data and also keeps track of site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognize unique visitors.
_ga_0J2F6JVWSD2 yearsThis cookie is installed by Google Analytics.
_gat_gtag_UA_84232734_11 minuteSet by Google to distinguish users.
_gid1 dayInstalled by Google Analytics, _gid cookie stores information on how visitors use a website, while also creating an analytics report of the website's performance. Some of the data that are collected include the number of visitors, their source, and the pages they visit anonymously.
YouTube2 yearsYouTube sets this cookie via embedded youtube-videos and registers anonymous statistical data. I embed YouTube videos in my articles/tutorials - you won't get the full experience of the articles if this is deactivated.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
CookieDauerBeschreibung
IDE1 year 24 daysGoogle DoubleClick IDE cookies are used to store information about how the user uses the website to present them with relevant ads and according to the user profile.
test_cookie15 minutesThe test_cookie is set by doubleclick.net and is used to determine if the user's browser supports cookies.
VISITOR_INFO1_LIVE5 months 27 daysA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.
YSCsessionYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.
yt-remote-connected-devicesneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
yt-remote-device-idneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SPEICHERN & AKZEPTIEREN
Unterstützt von CookieYes Logo