Programmatically Get Summary Comments at Runtime

Programmatically get Summary comments at runtime

The XML summary isn't stored in the .NET assembly - it's optionally written out to an XML file as part of your build (assuming you're using Visual Studio).

Consequently there is no way to "pull out" the XML summaries of each method via reflection on a compiled .NET assembly (either .EXE or .DLL) - because the data simply isn't there for you to pull out. If you want the data, you'll have to instruct your build environment to output the XML files as part of your build process and parse those XML files at runtime to get at the summary information.

c# getting interface method comments

The C# compiler csc.exe has a /doc option that outputs an external XML file having your triple-slash comments. This XML file is used by documentation generators (e.g. Sandcastle does this kind of thing).

That same option to export XML comments is available from Visual Studio. To set this compiler option in the Visual Studio development environment:

  1. Open the project's Properties page. For details, see How to: Set Project Properties (C#, J#).
  2. Click the Build property page.
  3. Modify the XML Documentation File property.

You can load up this XML file using an XML parser from the .NET framework, access the Types in it, and grab the related comments from around them.

You're right the C# compiler doesn't compile comments into the meta data. However Microsoft created triple-slash comments for export ability, so you can get a handle to them.

Instructions for processing the XML file are here on MSDN.


As an example, I enable the XML output file option and documented the following method:

/// <summary>
/// This method parses the given name for
/// capitalization.
/// </summary>
public void ParseStringCase(string name)
{
// behaviour of method...
}

It produces the following XML in a file in the bin/ folder....

<?xml version="1.0"?>
<doc>
<assembly>
<name>WindowsFormsApplication3</name>
</assembly>
<members>
<member name="M:WindowsFormsApplication3.Form1.ParseStringCase(System.String)">
<summary>
This method parses the given name for
capitalization.
</summary>
</member>
</members>
</doc>

Get XML Documentation Comments

If you don't want to use XML comments, you can store the description as metadata using the [Description] attribute, i.e:

[Description("This can have any description of the class")]
public class MyClass {}

You can then access the value of this attribute at run-time:

public static string GetDescription(Type t) {
return TypeDescriptor.GetAttributes(t)
.OfType<DescriptionAttribute>()
.Select(x => x.Description)
.FirstOrDefault();
}

e.g. GetDescription(typeof(MyClass))

Retrieve xml doc comments programmatically

Find xml

For assembly.dll it is named as assembly.xml, but installed by Framework SDK, Runtime itself doesn't contain .xml files. Users do not need API documentation.

Location is a bit more complex. It can be side by side with the dll, in the subdirectory named after current locale (e.g. C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\en) or even in some weird directory nearby. I would suggest searching for it in the way runtime looks for satellite assemblies.

Find element

To find element, you should prepare so called "xml-doc ID" from the metadata. AFAIR it is documented in C# language spec, and a bit in MSDN. See Processing XML documentation.

Get method or property xml remark from ducumentation to show in tooltip

It was discussed on SO several times, but for some reason it is extremely hard to find.

There are basically two options:

1) Use Roslyn. This is what you want if you have access to the sources. There is a great answer on this topic: How to read XML documentation comments using Roslyn

2) Parse xml documentation by yourself. Along with your binaries, you can find .xml files with all the type descriptions. You need to turn the generation on, before having them - go to solution properties->build and specify XML documentation file If you parse it you can retrieve any information you need. For each element, there is a separate member tag. It has attribute name which defines what element are you looking at. The name specified is has a prefix, which defines the type of the element - a type (T:), a property (P:), etc. The inners of the tag contain all the required info.

Here is an example:

<member name="T:MyNameSpace.MyTuple`2">
<summary>The summary</summary>
<typeparam name="TA">The first tuple type.</typeparam>
<typeparam name="TB">The second tuple type.</typeparam>
</member>

Please notice `2 in the end of the type name - this is because the type is generic.

Here is an example in powershell I used before:

function Get-Type-Xml-Description($typeName) {
$type = $assembly.GetTypes() | Where-Object { $_.Name -eq $typeName } | Select -First 1
if ($type -eq $null){
return $null
}

$tName = $type.FullName
$path = "T:"+$tName
$node = $xmlDocument.SelectSingleNode("//member[@name = '" + $path + "']")
return [Regex]::Replace($node["summary"].InnerText.Trim(), "\s+", " ")
}

It uses the $assembly$ to get the full name of a type, but if you know that already and you don't need to iterate over all types, you don't have to have the assembly.
Also you need to account generic type names, which have `[number of typeparams] in the end. This powershell example doesn't do this.

Good Practices for Method Summary XML Comments

In my opinion, you are correct that <summary> is probably the tag you will use most often to explain what exactly your method is meant to do. But if your methods have good, useful names, then expect that most developers will use that to make some assumptions about how the method should behave. For example, they assume that calling "GetName" probably has no side effects, and returns the name of the instance, regardless of what the comments say.

With that in mind, rather than writing paragraphs about what the method should be doing, I tend to focus my comments on any "gotcha"s that I am aware of, knowing that if someone uses my code, and it's not working the way they think it should, the first thing they will do is look at the documentation hoping for some guidance. Below are just a few examples of how I've used the various tags.

  • <returns> - Indicate that a return value may be null. Describe semantic difference between returning null vs. string.Empty
  • <remarks> - Great for explaining "gotcha"s, e.g. "The reader must be in a ready state, and the cursor positioned at the correct position to begin reading. The caller is responsible for closing the reader after this method completes." I usually add these comments as needed after fussing with an API for half an hour before realizing some silly detail that wasn't obvious.
  • <example> - Good APIs should be easy to use, but sometimes you can't help it. This is great for giving guidance on how the method was intended to be used (although you can't guarantee that's how it will be used). See example below.
<example>
var token = m_caller.GetAuthToken();
var result = m_caller.Call(method, token);
</example>

I'm sure there are hundreds of other examples I could dream up, but I hope that helps get you pointed in the right direction!

How to read XML documentation comments using Roslyn

You'll need to either:

  1. Look at the LeadingTrivia of the syntax that contains the XML doc comments
  2. Construct a Compilation, find the Symbol that has the XML doc comment and use the GetDocumentationComment() method on it.

A complete example:

using Roslyn.Compilers.CSharp;
using System;
using System.Linq;

class Program
{
static void Main(string[] args)
{
var tree = SyntaxTree.ParseText(@"
/// <summary>This is an xml doc comment</summary>
class C
{
}");
var classNode = (ClassDeclarationSyntax)tree.GetRoot().Members.First();
var trivia = classNode.GetLeadingTrivia().Single(t => t.Kind == SyntaxKind.DocumentationCommentTrivia);
var xml = trivia.GetStructure();
Console.WriteLine(xml);

var compilation = Compilation.Create("test", syntaxTrees: new[] { tree });
var classSymbol = compilation.GlobalNamespace.GetTypeMembers("C").Single();
var docComment = classSymbol.GetDocumentationComment();
Console.WriteLine(docComment.SummaryTextOpt);
}
}

How can I export XML code documentation in vb.net?

There are several tools that can generate a documentation in HTML or other formats out of the XML comments. Some of them:

  • VSdocman - the tool for generating API documentation from C# and VB projects. It can generate multiple formats, including HTML, CHM, PDF, Docx and others. It also provides WYSIWYG XML comments editor in Visual Studio. It is a commercial product and I'm the author.
  • Sandcastle Help File Builder - a set of tools that are used to create help files for managed class libraries containing both conceptual and API reference topics. Free.
  • DocFX - An extensible and scalable static documentation generator. Free.


Related Topics



Leave a reply



Submit