SubMain - CodeIt.Right The First Time!

/Community

Support Community for SubMain Products
 Home Products Services Download Purchase Support
in Search
 
Home Forums Blogs Tutorials/CIR Tutorials/GD Downloads
Welcome to SubMain Community Sign in | Join | Help

Tutorials

  • Publishing Custom Configured Coding Standards to Your Team

    Introduction

    CodeIt.Right Enterprise Edition installation package includes two modules for you to choose from - Team Configuration Module and Analysis Module. 

    The Team Configuration Module (TCM) is tailored for Team Leads and Architects.  With this module installed, you can configure your team guidelines by using profiles that best meet your team’s requirements.  You can also author additional custom rules and when everything is set up to your satisfaction, can deploy profiles to your team.

    The Analysis Module (AM), on the other hand, is the version you’ll usually want your team members to install.  In this version, the developer doesn’t have the option to author new rules or to modify profiles but must select a profile from those made available by the Team Lead.

    Publishing new or edited profiles from the TCM is easy and this tutorial will take you through it step by step.

    One thing to point out before we start is that when you first install the TCM one of the options in the installation asks you to choose the Shared Folder on the network.

    image1 

    This folder will be used to publish rule updates to the team.  If you don’t want to use the default location, you can always change the Shared Folder in the Options menu.  The same Shared Folder is also used for the Enterprise Edition statistics database, and is where the developers’ Analysis Module installations send their statistics for review and analysis.

    Publishing Profiles from the Team Configuration Module

    When you are ready to publish profiles to the team members who have the Analysis Module installed, open the Profile Editor and select the Publish menu item:

    image2

    The Publish dialog box shown below will then appear:

    image3

    In this dialog, select the profiles you want to push out to the team and click Finish.  If you a shared Dictionary, this can be published to the team by checking the Publish Shared Dictionary option at the bottom of the list.

    After the publishing has completed, you will see a confirmation message. Team members with the AM installed will now able to use all the published profiles and the dictionary, if selected.

    Rule Updates tab

    This tab is shown in the Publish Dialog only if the <CodeIt.Right installation folder>\Updates folder contains least one update folder, like the 20140121 example shown below.

    image4

    This folder contains child folders with updates that were downloaded by the TCM administrator from the SubMain web service. Each folder contains individual assemblies for each rule category and one UpdateConfig.xml file, as seen in the screenshot below.

    image5

    Here is an example of an UpdateConfig.xml file:

    <CirRuleUpdate sdkVersion="1.1.31.25" url="http://submain.com/blog/CategoryView,category,Rules.aspx" description="Rule Update 20140121" date="20140121" />

    Folders Used for Publishing

    Profiles are copied from c:\Users\<user>\Documents\SubMain\CodeIt.Right <edition> for VS20XX\Profiles\ to <publish folder>\Updates

    image6

    If the Publish Shared Dictionary option is selected, the shared dictionary is copied from c:\Users\<user>\Documents\SubMain\CodeIt.Right <edition> for VS20XX\Dic\user.dic to <publish folder>\

    image7

    The Wizard will publish all rule assemblies that are referenced in profiles that you select to be published.

    image8
     

    image9

    The <publish folder>\Updates folder has folders that each contain rule assemblies. Each folder has a name that should match SubMain.CodeItRight.Sdk.dll for that update.

    How Analysis Module Users Receive Updates

    Developers who have the Analysis Module version installed can synchronize their installation automatically or manually.  The necessary files are transferred or updated from the Shared Folder to the local CodeIt.Right installation. 

    The frequency for update checks is configured in the Auto Update option, which is accessible from CodeIt.Right -> Options -> Auto Update menu item in Visual Studio.   You can see the Auto Update options dialog in the screenshot below.

    image10

    The user can select to update every week, every month or manually.  There is also a Check Now button.

    Publishing Updates from a Build Machine

    For a build machine where  Visual Studio isn’t installed, you can use the CodeItRight.Cmd.exe Command  Line Options to publish updates.  In this case you use the /RuleUpdate switch – see CodeItRight.Cmd.exe Command Line Options for more information.

  • How to embed Images in a Generated Help File

    Step 1: Reference the Image from within the XML Comment

    You can use standard HTML syntax to insert the link to an image inside the comment.

    C#

    /// <summary> /// The ClassLibrary22.One namespace. /// </summary> namespace ClassLibrary22.One { /// <summary> /// A useful class. /// /// <para/> /// <img src="../{Imagefolder}/UML Diagram 1.jpg" /> /// /// </summary> public class Class2 { /// Class code here } }

    VB

    ''' <summary> ''' A useful class. ''' ''' <para/> ''' <img src="../{Imagefolder}/UML Diagram 1.jpg" /> ''' ''' </summary> Public Class Class2 ' Class Code here End Class

    In the example above, "A useful class." is the standard descriptive text of a comment. The following (optional) "<para/>" paragraph tag ensures there is some space between this main comment and the image.

    The "img" image tag identifies the location and name of the file to be displayed. The location of the "Imagefolder" will be covered in the next step.

    Step 2: Configure the Image Folder and Build the Help File

    In the Visual Studio main menu, select Tools > GhostDoc Pro > Build Help File.

    image1

    In the Dialog that appears next, select the folder that contains the image you want to include. (In this example this will be the file named "UML Diagram 1.jpg" which is located in the Pictures folder.)

    image2

    Next, click on the OK button to build the Help file.

    When the Help file has been generated, you will see the inserted image in the Help file:

    image3

    Optional Step 3: Add additional Text Comments for the Image

    If the image needs further text explanation, you can add this by extending the comment in the usual way: For example:

    C#

    /// <summary> /// A useful class. /// /// <para/> /// The following diagram describes the database structure: /// <para/> /// <img src="../{Imagefolder}/UML Diagram 1.jpg" /> /// /// </summary>

    VB

    ''' <summary> ''' A useful class. ''' ''' <para/> ''' The following diagram describes the database structure: ''' <para/> ''' <img src="../{Imagefolder}/UML Diagram 1.jpg" /> ''' ''' </summary>

    The additional text will appear above the image:

    image4

    Optional Step 4: Add an Alt tag to the Image.

    Although the image will be embedded in the Help file, you may still wish to follow the standard procedure of including a text description of the image if the user hovers the mouse over it. You do this in the usual way using an Alt tag:

    C#

    /// <summary> /// A useful class. /// /// <para/> /// The following diagram describes the database structure: /// <para/> /// <img src="../{Imagefolder}/UML Diagram 1.jpg" alt="UML Diagram" /> /// /// </summary>

    VB

    ''' <summary> ''' A useful class. ''' ''' <para/> ''' The following diagram describes the database structure: ''' <para/> ''' <img src="../{Imagefolder}/UML Diagram 1.jpg" alt="UML Diagram" /> ''' ''' </summary>
  • Conceptual Content - How to include Tables

    Introduction

    In our earlier tutorial we describe the basic steps needed to create conceptual content in your Help files. It covers topics such as descriptions of the various file types you'll need to know about and how the conceptual content should be structured for it to be successfully compiled into a Help file with GhostDoc Enterprise.

    In this tutorial, I'm going to describe how you can extend your options by adding tables to conceptual content help pages.

    The Basic Table Elements

    A basic table will have column headers and several rows and columns of data. Something like this:

    image1

    The core elements used to create a table are table, tableHeader, row, and entry as you will see in the code snippet below that creates the example table. I've resized and colored some sections in to order to highlight them for the discussion that follows the code:

    <?xml version="1.0" encoding="utf-8"?> <topic id="0a179390-b0a8-48e0-8527-7cca1d66ad80" revisionNumber="1"> <developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink"> <introduction> <para> An example of a table element that includes a table header and row, entry and para elements. </para> </introduction> <table> <tableHeader> <row> <entry><para>Feature</para></entry> <entry><para>GhostDoc</para></entry> <entry><para>GhostDoc Pro</para></entry> </row> </tableHeader> <row> <entry><para>Document This</para></entry> <entry><para>Yes</para></entry> <entry><para>Yes</para></entry> </row> <row> <entry><para>Document Type</para></entry> <entry><para>No</para></entry> <entry><para>Yes</para></entry> </row> . . . Some row elements omitted for brevity <row> <entry><para>Rebuild Option</para></entry> <entry><para>Yes</para></entry> <entry><para>Yes</para></entry> </row> </table> </developerConceptualDocument> </topic>

    The parent element is of course the table element which will contain all the remaining elements that make up the structure.

    You'll usually want column headers at the top of the table. For this you use the tableHeader element which will create the formatting that makes the header stand apart from the body of the table by means of its gray background. The sub-elements inside the tableHeader are row and entry elements that I'll describe next.

    Each individual row (including the tableHeader formatted row) comprises a row element and a number of entry elements. Obviously, the number of entry elements will control how many columns the table will have. It is permissible to have empty cells; just create an entry element with no content or use the non-breaking space markup of &#160; or &nbsp;

    The entry elements contain the visible data. In this example, I've used para elements to display plain text, but you can use other MAML elements - images, links, code snippets, and so on - in cells if you want to.

    Adding Titles

    In addition to the column headers created with the tableHeader elements, you may want something more in the way of table title and maybe even a sub-title. You can add the main title by using the aptly named title element. However if you insert the title element into the table element:

    <table> <title>GhostDoc Pro Comparison Table</title> <tableHeader> <row> <entry><para>Feature</para></entry> <entry><para>GhostDoc</para></entry> <entry><para>GhostDoc Pro</para></entry> </row> </tableHeader> . . . Remaining markup omitted

    the resulting display isn't particularly eye catching:

    image2

    You can highlight the text by making it bold, italic and underlining it (covered in a separate tutorial) { add link when posted }. But if you want it to really stand out then there's a trick you can use as shown in the snippet below:

    <section> <title>GhostDoc Pro Comparison Table</title> <content> <table> <tableHeader> <row> <entry><para>Feature</para></entry> <entry><para>GhostDoc</para></entry> <entry><para>GhostDoc Pro</para></entry> </row> </tableHeader> <row> <entry><para>Document This</para></entry> <entry><para>Yes</para></entry> . . . Remaining markup omitted

    This places the table inside a section element and then uses the title element at the section level. The default format of this title is more colorful and larger than the title element down at table level.

    Note that in addition to the section element you must also include a content element as shown in the snippet. If you omit this, none of the content inside the section element will be visible on the page. Don't forget to insert the closing tags of these two elements (not shown in the snippet) if you use this technique.

    image3

    If you want a sub-title between the main title and the table headers, you can insert a second title element inside the table:

    <section> <title>GhostDoc Pro Comparison Table</title> <content> <table> <title>Check what's included in each version:</title> <tableHeader> <row> . . . Remaining markup omitted

    image4

    Nested Tables

    Creating nested tables is quite easy. As you'd expect you create child tables inside a parent, locating the whole of the child table inside an entry in a single row of the parent table. Here's an example of nested tables in action:

    image5

    In the above example the GhostDoc image is the first (and only) entry in the first row of the parent table.

    <table> <title>Check out the features table:</title> <row> <entry> <mediaLink> <image xlink:href="GhostDoc"/> </mediaLink> </entry>

    All the column headers, rows and columns at the right side are housed in a child table that's inside the second entry of the first row of the parent table:

    <table> <title>Check out the features table:</title> <row> <entry> <mediaLink> <image xlink:href="GhostDoc"/> </mediaLink> </entry> <entry> <table> <tableHeader> <row> <entry><para>Feature</para></entry> <entry><para>GhostDoc</para></entry> <entry><para>GhostDoc Pro</para></entry> </row> </tableHeader> <row> <entry><para>Document This</para></entry> . . . Remaining markup omitted

    While this may look complex here on paper, in theory it's quite simple. You can place a completely separate table inside an entry of another table, just as easily as you'd place a para in there to display text.

    The above example can be extended in other ways. For instance, the first row of the parent table can contain everything you see in the screenshot above and then that parent table can have further row and entry elements that display something more. In the next screenshot, you can see this in action:

    image6

    Everything I've highlighted with the blue rectangle is part of the first row of the parent table. The text in the red rectangle at the bottom is part of the second row of the parent table. As before, the rows and columns at the top right that compare the features are all part of the second entry of row 1 of the parent.

    The markup that creates this is rather long and an abbreviated version is shown below:

    <?xml version="1.0" encoding="utf-8"?> <topic id="4f4e7777-2d64-4f9e-8e82-72d465af3098" revisionNumber="1"> <developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink"> <introduction> <para> A nested table example that includes an image and a sub-table inside the parent. </para> </introduction> <section> <title>GhostDoc Pro Comparison Table</title> <content> <table> <title>Check out the features table:</title> <row> <entry> <mediaLink> <image xlink:href="GhostDoc"/> </mediaLink> </entry> <entry> <table> <tableHeader> <row> <entry><para>Feature</para></entry> <entry><para>GhostDoc</para></entry> <entry><para>GhostDoc Pro</para></entry> </row> </tableHeader> <row> <entry><para>Document This</para></entry> <entry><para>Yes</para></entry> <entry><para>Yes</para></entry> </row> . . . Intermediate markup removed for brevity <row> <entry><para>Rebuild Option</para></entry> <entry><para>Yes</para></entry> <entry><para>Yes</para></entry> </row> </table> </entry> </row> <row> <entry> <para>Compare GhostDoc features</para> </entry> <entry> <para>Identify which version you need</para> </entry> </row> </table> </content> </section> </developerConceptualDocument> </topic>

    The highlighted markup above identifies how the final row of text is created.

    Summary

    Sometimes the only way to present data in a user friendly way is to use a table. As you can see, it is very easy to create tables for your conceptual content - from basic text only single tables to complex nested tables that include media or other kinds of formatted content.

  • Conceptual Content - How to Include Bulleted and Ordered Lists

    Introduction

    In an earlier tutorial I demonstrated the basic components used to create conceptual content. That tutorial also explained the basic building blocks, including the file types used and also how the conceptual content should be structured in order for it to be successfully compiled into a help file.

    In this tutorial, I'm going to look at how you can refine the layout of conceptual content pages by adding various kinds of lists.

    Bulleted Lists

    Although you can of course simply type in para items one below the other in order to create a list, the user experience will often be improved if you use bullets or numbers. Here's a simple example of a help page that contains a bulleted list:

    image1

    To create this kind of list in the markup you use a list element with the class name "bullet". Then, within that list element you add individual listItem elements (Note the camel casing used in the name of the element here). In each individual listItem you can add whatever content you want to display. The example above uses para elements to hold the content but, as you'll see later in this tutorial you're not limited to these.

    The markup that creates the help page shown above is as follows. I've highlighted the xml that creates the list:

    <?xml version="1.0" encoding="utf-8"?> <topic id=" 949a345b-d8a6-4009-9b58-efb26ab4914c" revisionNumber="1"> <developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink"> <introduction> <para> Bulleted Lists are created using "list class="bullet" and individual listItems. </para> </introduction> <list class="bullet"> <listItem> <para> Public </para> </listItem> <listItem> <para> Private </para> </listItem> <listItem> <para> Protected </para> </listItem> <listItem> <para> Friend </para> </listItem> <listItem> <para> Protected Friend</para> </listItem> </list> </developerConceptualDocument> </topic>

    If you need to refresh your memory on how the above .aml file is referenced in the .content file, you can read up on it here.

    Ordered Lists

    Creating ordered lists, like the one shown below is just as easy.

    image2

    In this case, the class name you use is "ordered" and the list is highlighted in bold in the markup below:

    <?xml version="1.0" encoding="utf-8"?> <topic id="57a1d911-0915-4865-c4514-581u3gf49s88" revisionNumber="1"> <developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink"> <introduction> <para> Ordered Lists are created using "list class="ordered" and individual listItems. </para> </introduction> <list class="ordered"> <listItem> <para> Public </para> </listItem> <listItem> <para> Private </para> </listItem> <listItem> <para> Protected </para> </listItem> <listItem> <para> Friend </para> </listItem> <listItem> <para> Protected Friend</para> </listItem> </list> <relatedTopics> <link xlink:href="949a345b-d8a6-4009-9b58-efb26ab4914c" /> </relatedTopics> </developerConceptualDocument> </topic>

    You'll see that the example above includes a link to the bulleted list page. These lists can be used as just one portion of a help page and you can include different kinds of formatted content on the same page as shown above.

    Summary

    Lists can be very useful to break up text into logical and easily digestible chunks. Although the above examples have displayed text as their list items, it is possible to use other visual elements, such as images, or differently formatted text. However MAML isn't very flexible in this regard and in many cases if you try and insert over-complex visual elements as list items, the results won't be as neat as you might want - defeating the purpose of using a list in the first place. Where you need to break the display up into clearly discrete chunks, it's often better to use section elements. But for simple lists of text, the listItem element as shown here is ideal.

  • How to submit Visual Studio crash log to SubMain support

    If Visual Studio Crashes While You're Using One of SubMain Add-Ins

    Even though we put a huge amount of time and resources into getting our products right, things can still sometimes go wrong.  If you've experienced a Visual Studio crash while using one of our products, we'd appreciate your help with troubleshooting the issue and so we can resolve your particular issue.

    To do this, please follow these steps:

    1. When Visual Studio crashes, it displays this warning message:

      VS_crash_1
    2. Please wait for Visual Studio to finish it’s diagnostics, (i.e.don’t click on the Cancel button, even though it’s something frustrating to have to wait!) and you’ll see the following message:

      VS_crash_2
    3. Next, click the Debug button and Visual Studio will display the message shown below:

      VS_crash_3
    4. The best option here is to choose “New instance of the same version of Visual Studio 20xx”, choosing the Visual Studio version you were running when the crash occurred.

      After opening this new instance of Visual Studio, take a screenshot of the call stack information:

      Capture
    5. Finally, please email us at support@submain.com with the call stack information you’ve collected – a screenshot will do. We will investigate and get back to you with a suggested solution without delay.

    We are proud of our products and want you to get the best possible experience when using them.

    The SubMain Team

  • Conceptual Content - Adding Custom Content to API Documentation created with GhostDoc

    Table of Content

    Introduction

    GhostDoc Pro Enterprise Edition includes a feature that lets you add Conceptual Content pages in your help files. Conceptual Content can include all those useful pieces of information that your users need, but which won't be picked up directly from the compiled comments in your code. This information will vary from project to project, but may include things like code snippets, hints and tips, tutorials, notes for users, and so on. In fact, any additional information you want your users to find in the help file.

    If you don't have GhostDoc Enterprise installed, you can download the free 14 day evaluation copy here.

    In order to build this additional content and incorporate it into the compiled help file, you have to create and edit a number of files. These are then added to the help file that GhostDoc Pro generates. These files use Microsoft Assistance Markup Language (MAML), an XML markup with a schema that describes the structure of the conceptual help content. MAML includes several distinct content types, each one aimed at creating a type of document with a specific task.

    The Conceptual Content model was introduced as Sandcastle by Microsoft in 2007 and that concept allows us to extend the documentation that's generated from the API XML comments by adding custom content. This tutorial will walk you through GhostDoc's implementation of the original Sandcastle conceptual content feature.

    The schema for the conceptual content type is shown below:

    image1

    The ClassLibrary1 Sample Project

    To help you learn how to add conceptual content, we have included a sample project in the GhostDoc Enterprise Edition installation. To locate this project, navigate to the Program Files Installation folder of GhostDoc Pro (typically C:\Program Files or C:\Program Files (x86)) then navigate down through the path - /SubMain/GhostDoc Enterprise/Samples/Conceptual Content, and then extract the files from the ClassLibrary1.zip file. For your convenience we also included the sample project download link – see #1 under Additional Resources at the end of this post.

    This very simple project has been created to introduce you to the files that are required and examples of content you could include. When you're ready to create your own conceptual content, you can copy files from the sample and paste them into your own project. All that's needed then is for you to edit the content to meet your own needs.

    The screenshot below shows the generated help file for the sample project, including the conceptual content files that will be described in this tutorial.

    image2

    For ease of reference, the next screenshot shows the file and folder structure of the sample project.

    image3

    Summary of the Files Used to Create Conceptual Content

    Although I'll work through the conceptual content related files in detail in the sections that follow, you might find it useful to have a quick summary from the start.

    ClassLibrary1.content : The role of this file is to keep an index of all the core required information about topics that are included in the conceptual content.

    ClassLibrary1.sln.GhostDoc.xml :This file is used by GhostDoc to keep track of your choices about the kind of help file you want to generate. You'll manually edit this file as part of the conceptual content creation process.

    ClassLibrary1.snippets :If you include a Code Snippets topic in the help file, the details of the code will be stored in this file.

    ClassLibrary1.tokens :If you include links to external sites in a topic, this file is where you store the details of those links.

    MediaContent.xml :If you include media - like the Ghost image shown in the screenshot above - in any of your topics, details of that media will be stored in this file.

    Content Folder :This folder contains a separate file for each conceptual content topic page you include in your help file.

    Help Folder :This folder will contain the generated help file once you've created it with GhostDoc. You can regenerate the help file as many times as you like, so you can check progress of your conceptual content creation.

    Media Folder :Media files, such as the GhostDoc PNG file used in the example above are stored in this folder.

    Content Layout File - ClassLibrary1.content

    One of the key files you need to know about is the Content Layout file. As its name implies, this file identifies the topics that will be included in the conceptual content section of the help file. It dictates the order of the topics, assigns an id, a title and help keywords for each topic. The content layout file used in the sample project is shown below:

    <?xml version="1.0" encoding="utf-8"?> <Topics> <Topic id="90a1d911-0315-4865-a414-58189cca1ecb" visible="True" isDefault="true" title="Welcome"> <HelpKeywords> <HelpKeyword index="K" term="Welcome" /> </HelpKeywords> </Topic> <Topic id="24504fda-d3ef-4dd9-8335-6db8b25d00f2" visible="True" title="License Agreement"> <HelpKeywords> <HelpKeyword index="K" term="License Agreement" /> </HelpKeywords> </Topic> <Topic id="9bef5420-7560-47d9-98ce-0b5d5f46567a" visible="True" title="Code Snippets File"> <HelpKeywords> <HelpKeyword index="K" term="File Types, code snippets" /> </HelpKeywords> </Topic> <Topic id="2BE96AFB-6198-4796-A0CB-6B811549E14C" visible="True" title="Tutorial"> <HelpKeywords> <HelpKeyword index="K" term="Tutorial" /> </HelpKeywords> </Topic> <Topic id="53c8f54a-85fb-4857-8adc-0f137d6246a4" visible="True" noFile="true" isExpanded="true" title="Custom Node"> <Topic id="aba20266-8020-4e8c-96ad-f28e42c4db7b" visible="True" title="Custom Page"> <HelpKeywords> <HelpKeyword index="K" term="Custom Page" /> </HelpKeywords> </Topic> </Topic> </Topics>

    The content layout file for the sample project is named ClassLibrary1.content. To re-use the content layout file from the sample project, copy and paste the ClassLibrary1.content file, renaming it as required. Then edit the values of the elements and attributes, while maintaining the overall structure of the original.

    You don't have to use the '.content' file extension as we have in the sample, but we recommend that you do unless you have reasons to use a different one. The use of .content file extension here follows the naming conventions from the original concept and may help you become familiar with the topic more quickly and help you to understand other examples you may find on the web or elsewhere. And of course those who are familiar with the original Sandcastle feature will find it easier to get to grips with the GhostDoc implementation because we've kept to the naming conventions.

    Alternatively, to create this file from scratch, add a new XML file to the project and save it with the file name of your choice. Then add the XML structure as shown in the example above.

    Whichever method you use to create this file, note the following key points:

    • The ID must be unique; using a GUID is recommended.
    • The title attribute is required
    • You add one or more values to the term attribute of the HelpKeyword. This ensures that these items will appear in the list on the Index tab of the help file and that the user will be able to find this topic if they use any of these terms in the Search tab. Note that if you want to include multiple values for the term, they must be separated by a comma.

    You'll see that individual Topic elements in the file use various other attributes, all of which I think are self-explanatory.

    The first three Topics in this sample file are straightforward - Welcome, Code Snippets File and Tutorial. The final topic - Custom Node - is included to demonstrate that it's easy to add nested topics in the conceptual content of the help file. In this case, Custom Node has one child topic - Custom Page - but it is permissible to add more if you need them. You simply add further nested topics inside the Custom Node element.

    Each Topic in the ClassLibrary1.content file, with the exception of the Custom Node topic, is related to a separate individual topic file which contains the content to be displayed on its help page. In the sample project, these individual topic files are saved in the Content folder of the project. As you'll find later when I deal with the ClassLibrary1.sln.GhostDoc.xml file, you can choose to store these files in another folder of your choice.

    I'll deal with each of these individual topic files next.

    Topic Files

    You create a separate Topic File with the .aml file extension for each conceptual content topic you want to include in the help file. I'll begin with the Welcome.aml file which you can find in the Content folder of the sample project.

    Welcome.aml

    The generated output for the Welcome page in the sample file looks like this:

    image5

    The Welcome.aml file that creates this page is structured as shown below:

    <?xml version="1.0" encoding="utf-8"?> <topic id="90a1d911-0315-4865-a414-58189cca1ecb" revisionNumber="1"> <developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink"> <mediaLink><image placement="center" xlink:href="GhostDoc"/></mediaLink> <introduction> <para>This is help file sample contains information on how use conceptual content to generate help file. You can find more information at <link xlink:href="2BE96AFB-6198-4796-A0CB-6B811549E14C" /> </para> </introduction> <relatedTopics> <link xlink:href="9bef5420-7560-47d9-98ce-0b5d5f46567a" /> </relatedTopics> </developerConceptualDocument> </topic>

    The key points to note from this sample file are:

    • The topic id value must match the value of this topic's id in the .content file, otherwise the build will fail.
    • The main body of the topic must be placed inside the developerConceptualDocument tags. The 'Welcome' header (seen in blue at the top of the topic in the screenshot) is created and inserted automatically based on the title attribute in the .content file.
    • The xml namespaces shown above are required in all topic files.
    • To insert an image into the body of the topic, you use a mediaLink element which references a named image file, in this case an element with the id of 'GhostDoc'. I'll explain how this reference works when I deal with the MediaContent.xml file later in this tutorial.
    • The introduction element contains the main body of the text in the topic. You can include multiple paragraphs inside this section.
    • The introduction in this topic includes a link to another topic in the same help file. To do this, include a link inside the para and reference the id of the topic you want to link to. The easiest way to find the GUID is by looking in the Content Layout file (ClassLibrary1.content in the sample). The help compiler will automatically find the title of the linked topic and insert it here.
    • To provide the link that you can see in the Other Resources section, use the syntax shown in the example above. The procedure is the same as described in the previous bullet. You can of course add multiple links.
    CodeSnippetsFile.aml

    In the code snippets topic in the sample, the help file display looks like this:

    image6

    The content of the CodeSnippetsFile.aml file that creates this page is shown below:

    <?xml version="1.0" encoding="utf-8"?> <topic id="9bef5420-7560-47d9-98ce-0b5d5f46567a" revisionNumber="1"> <developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink"> <introduction> <para>The code snippets file allows you to define code samples outside of conceptual topic files.</para> </introduction> <section> <title>Example Output</title> <content> <para>Define a class</para> <codeReference>ClassDefinition#Define</codeReference> </content> </section> <relatedTopics> <link xlink:href="90a1d911-0315-4865-a414-58189cca1ecb" /> </relatedTopics> </developerConceptualDocument> </topic>

    Follow the guidelines below when creating your own code snippets files. Although several of them are the same as for the Welcome.aml file described above, there are some differences.

    • The topic id value must match the value of this topic in the .content file, otherwise the build will fail.
    • The main body of the topic must be placed inside the developerConceptualDocument tags. The 'Code Snippets File' header (seen in blue at the top of the topic in the screenshot) is created and inserted automatically.
    • The xml namespaces shown above are required in all topic files.
    • The introduction element contains the main body of the text in the topic. You can include multiple paragraphs inside this section.
    • The section element houses the code snippets display. In this example, there is a title and a content sub-element that is used to hold text (the string "Define a class").
    • The codeReference element references the id ("ClassDefinition#Define") of a code snippet which (in this sample project) is located in the ClassLibrary1.snippets file. I'll cover that snippet in more detail when I deal with the ClassLibrary1.snippets file later. Be aware though that the conceptual content compiler knows how to format the presentation of code snippets that are placed inside codeReference tags.
    • To include links in the Other Resources section, use the syntax shown in the example above inside the relatedTopics tags, inserting the GUID of the topic you want to link to. The help compiler will automatically find the title of the linked topic and insert it here.
    Tutorial Topic

    The Tutorial topic in the sample project looks like this:

    image7

    You'll notice that on the first line of the main body of text on that page, the word 'Tutorial' is a hyperlink. You can insert hyperlinks to external URLs like this very easily. Here's the markup for the Tutorial Topic page:

    <?xml version="1.0" encoding="utf-8"?> <topic id="2BE96AFB-6198-4796-A0CB-6B811549E14C" revisionNumber="1"> <developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink"> Please see the following <token>tutorial</token> on SubMain web site and learn about custom help file content using Conceptual Content with GhostDoc. </developerConceptualDocument> </topic>

    The text to be displayed, as with the other topics, is inside the body of the developerConceptualDocument element. In order to include a hyperlink, you use the <token> tag as shown above. The word 'tutorial' inside the token tag references the id of a token whose details are contained in the ClassLibrary1.tokens file. I'll be dealing with that file shortly, but for now it's enough to know that by referencing that token id, the required hyperlink can be invoked and an external page will be displayed.

    Custom Page Topic

    The Custom Page topic (shown below) simply displays the text content 'Custom Page'.

    image8

    The CustomPage.aml file in the Contents folder looks like this:

    <?xml version="1.0" encoding="utf-8"?> <topic id="aba20266-8020-4e8c-96ad-f28e42c4db7b" revisionNumber="1"> <developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink"> Custom Page </developerConceptualDocument> </topic>

    As with the other topics we've described, the main content is placed inside developerConceptualDocument tags. Although this simple example uses only two words, you can use any of the elements that are included in the other example topics - mediaLink, introduction, para, etc. plus more, such as lists, tables, warnings, and so on.

    Custom Node Topic

    The Custom Node Topic example in the sample file is slightly different from the other topics. When you navigate the nodes in the help file created in the sample project, you'll find that selecting the Custom Node topic doesn't cause a new page to be displayed. To demonstrate this, in the screenshot below, although Custom Node has been selected, you'll see that the previous topic - Welcome - is still displayed:

    image9

    This is a useful feature if you want a parent node (in this case, Custom Node) that works as an empty header for one or more child nodes, such as the Custom Page in the example above. However, some users may find it counter-intuitive to have a node where there is no visual feedback when it is clicked. So if you do want to have content in the parent node, you can easily do so.

    Here is the markup from the original example:

    <Topic id="53c8f54a-85fb-4857-8adc-0f137d6246a4" visible="True" noFile="true" isExpanded="true" title="Custom Node"> <Topic id="aba20266-8020-4e8c-96ad-f28e42c4db7b" visible="True" title="Custom Page"> <HelpKeywords> <HelpKeyword index="K" term="Custom Page" /> </HelpKeywords> </Topic> </Topic>

    Note that the noFile attribute is set to "true". This is the attribute that controls whether the compiler looks for a topic file in the Content folder to associate with this topic. In order to include content in this topic, the first step is to either change the value of noFile to "false", or simply delete that attribute because false is the default value.

    Now that the help builder has been asked to find a topic file, the next step is to create it. The easiest way to do this is to copy one of topic files from the sample project, paste it into the Content folder of the solution and rename it to CustomNode.aml. I will use the Custom Page topic and edit that, but you can of course use any of the Topic files if you want to or build a new file from scratch.

    Here is the original markup from the file I've copied:

    <?xml version="1.0" encoding="utf-8"?> <topic id="aba20266-8020-4e8c-96ad-f28e42c4db7b" revisionNumber="1"> <developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink"> Custom Page </developerConceptualDocument> </topic>

    The two items that need to be edited are the topic id and the text content. So, first copy the topic id for the Custom Node topic from the ClassLibrary1.content file and paste it to replace the topic id in the file you are editing.

    Then, inside the developerConceptualDocument tags, insert the content you want to display. For this example, I've used the introduction tag containing two paragraphs, but you can use any of the types of content shown in the sample files. I've also added two relatedTopics links, one to the Welcome page and one to the child topic of this page. The following markup creates the result you can see in the screenshot that immediately follows it:

    <?xml version="1.0" encoding="utf-8"?> <topic id="53c8f54a-85fb-4857-8adc-0f137d6246a4" revisionNumber="1"> <developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink"> <introduction> <para> This is the parent custom node. With the noFile attribute set to false, this topic content is now visible.</para> <para> You can choose not to have any content by setting noFile to true. </para> </introduction> <relatedTopics> <link xlink:href="90a1d911-0315-4865-a414-58189cca1ecb" /> <link xlink:href="aba20266-8020-4e8c-96ad-f28e42c4db7b" /> </relatedTopics> </developerConceptualDocument> </topic>

    image10

    The ClassLibrary1.sln.GhostDoc.xml file

    This key file is generated when you choose the Build Help File option in the Tools > GhostDoc Enterprise menu in Visual Studio.

    image11

    It contains all the settings needed to generate the help file. For a standard help file (one without conceptual content) you won't need to edit this file because all the values are assigned based on your choices in the Build Help File dialog:

    image12

    But when you want to create a help file that does include conceptual content, you do need to edit the ConceptualContent section of this file.

    By default, when you create a new project, the automatically created .sln.GhostDoc.xml file will include a skeleton section as shown below:

    <ConceptualContent> <ContentLayout /> <MediaContent /> </ConceptualContent>

    Compare the above snippet with the same section in the ClassLibrary1 sample project:

    <ConceptualContent> <ContentLayout file="ClassLibrary1.content" folder="Content\" /> <MediaContent file="MediaContent.xml" folder="Media\" /> <CodeSnippetsFile>ClassLibrary1.snippets</CodeSnippetsFile> <TokensFile>ClassLibrary1.tokens</TokensFile> <AdditionalContentFolder>Other\</AdditionalContentFolder> </ConceptualContent>

    You can see that all those key resource files - ContentLayout, MediaContent, CodeSnippetsFile, and TokensFile - now reference specific files in the project. And where appropriate, the folder that contains child files is also named; in this case, the Content and Media folders.

    (We have also included an AdditionalContentFolder in the example so you know it's available, but we haven't added any additional files in the sample.)

    When you build your own conceptual content, you have to edit this sln.GhostDoc.xml file to reflect the names of the files and folders that you want to use. Our sample reflects the accepted naming conventions, but you can use other names if you wish.

    This portion of the file pulls all the conceptual content together, so it's vitally important that you correctly name all the files and folders you want to use.

    Looking now at that list of files and folders above, I've already covered the ClassLibrary1.content file and the files in the Content folder. All that remain to be described are the MediaContent.xml, ClassLibrary1.snippets and ClassLibrary1.tokens files.

    Media Content file - MediaContent.xml

    The MediaContent.xml file stores the information needed to locate and display media displayed on topic pages. This is a single image in the sample project, but you can include more in your own help files' conceptual content. Here is the MediaContent.xml file from the sample project:

    <?xml version="1.0" encoding="utf-8"?> <stockSharedContentDefinitions> <item id="GhostDoc"> <image file="ghostdoc100x100.gif"> <altText>GhostDoc</altText> </image> </item> </stockSharedContentDefinitions>

    The key points to note about this file are:

    • All the media content is placed inside a stockSharedContentDefinitions tag.
    • Each individual media item (in this example there is only one) is created as a separate element and given a descriptive id.
    • The source of the media (in this case a gif image file) is referenced by file name only, even though this file is stored in the Media sub-folder. The conceptual content builder will be able to find this file at compilation time because the required path is referenced in theClassLibrary1.sln.GhostDoc.xmlfile (See the preceding section for the relevant code snippet):
                                 <MediaContent file="MediaContent.xml" folder="Media\" />
    • The altText value is optional but recommended as best practice for a better user experience.

    Snippets file - ClassLibrary1.snippets

    The .snippets file (in the sample, ClassLibrary1.snippets) is used to hold the individual code snippets that are displayed in the Code Snippets Topic files. In the sample project, there is just a single code snippets topic.

    The output of the code snippets topic looks like this:

    image6

    Two files are used in the creation of code snippets topics. I dealt with CodeSnippetsFile.aml earlier, in the Topic Files section.

    The second file used for code snippets is the .snippets file that I'm covering in this section.

    In the sample project it has the following content:

    <?xml version="1.0" encoding="utf-8" ?> <!-- This is an example code snippets file --> <examples> <item id="ClassDefinition#Define"> <sampleCode language="CSharp"> public class CSharpClass() { // Members go here } </sampleCode> <sampleCode language="VisualBasic"> Public Class VBClass ' Members go here End Class </sampleCode> </item> </examples>

    If you refer back to the earlier section that deals with the CodeSnippetsFile.aml, you'll see that the file has a <content> tag which contains para and codeReference elements:

    <content> <para>Define a class</para> <codeReference>ClassDefinition#Define</codeReference> </content>

    Notice that the value of the codeReference is "ClassDefinition#Define", which is the item id of the required snippet that's stored in the ClassLibrary1.snippets file.

    The sampleCode tags hold the actual code you want to display. You can see in the two examples above that snippets are shown in both C# and VB. The language attribute on the sampleCode element dictates the language name that's displayed in the header of each snippet. You are not limited to these two languages and can include snippets from other popular languages, such as F#, JavaScript, etc. Just insert the language name in the language attribute of the sampleCode element.

    Tokens File - ClassLibrary1.tokens

    The .tokens file contains details of external links that can be included in topics. In the sample project, the Tutorial.aml file includes a link that will bring you to this tutorial on the SubMain web site.

    image7

    The markup in the ClassLibrary1.tokens file is:

    <?xml version="1.0" encoding="utf-8"?> <content xml:space="preserve" xmlns:ddue="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink"> <item id="tutorial"> <ddue:externalLink xmlns:ddue="http://ddue.schemas.microsoft.com/authoring/2003/5"> <ddue:linkText>Tutorial</ddue:linkText> <ddue:linkUri>http://submain.com/fwlink/ghostdoc/tutorial/conceptual/</ddue:linkUri> <ddue:linkTarget>_blank</ddue:linkTarget> </ddue:externalLink> </item> </content>

    Note the following guidelines:

    • You should place all the content inside a <content> tag and include the xml namespaces shown above.
    • Each individual item must be placed inside an item tag and assigned an id - in this example, it's "tutorial". This id is referenced in line 7 of the Tutorial.aml file that I described earlier.
                          Please see the following <token>tutorial</token> on SubMain web site and learn about custom help file content using Conceptual Content with GhostDoc.
    • The linkText element contains the string that will be displayed as the text of the hyperlink in the Tutorial.aml file.
    • The linkUri identifies the URI of the external resource that will be navigated to.
    • The linkTarget element in this example has been set to _blank and in the case of chm help files will make the linked page open in a new window inside the help file

    Summary

    This tutorial and the sample project are designed to bring you up to speed on the core features of conceptual content when used with GhostDoc Enterprise Edition. The original Sandcastle project and Microsoft's MAML allow for more types of content to be displayed and you may want to read further once you've mastered the basics covered in this sample here. The original MAML help file created by Microsoft can be downloaded here. Also see the Sandcastle MAML Guide link (#3) under Additional Resources below.

    In many projects, including conceptual content in your help files will improve the users' experience and may reduce the number of clarification requests you receive at your help desk. It doesn't take a huge amount of work or time and once you are familiar with how the .xml and .aml files link together you can very quickly add value to the GhostDoc generated help files.

    If you don't have GhostDoc Enterprise installed, you can download the free 14 day evaluation copy here.

    Additional Resources

    1. Download GhostDoc Conceptual Content Sample Project
    2. Download MAML Reference Help File
    3. Sandcastle MAML Guide
    4. Conceptual Content - How to Include Bulleted and Ordered Lists
    5. Conceptual Content - How to include Tables
  • How to integrate CodeIt.Right with TeamCity

    You can integrate CodeIt.Right with TeamCity by following these steps:

    1.   Download and install the CodeIt.Right Enterprise Edition.  Note that this integration only works with the Enterprise version of CodeIt.Right. 

    2.   Navigate to the directory where you installed CodeIt.Right and then run SubMain.CodeItRight.Registration.exe with the following parameters (use your licensed name and license key): 

    SubMain.CodeItRight.Registration.exe /user:"<user name>" /license:"<license key>" /allUsers 

    The /allUsers switch registers CodeIt.Right so it can be run under any user on the TeamCity server including Local System account.

    Here is complete list of command line switches if you need to run it behind a firewall:

    /user or /u - Licensee name
    /license or /l - License key
    /allUsers or /a - Register for All Users
    /proxyHost or /h - Proxy host
    /proxyPort or /p - Proxy port
    /proxyUserName or /s - Proxy user name
    /proxyPassword or /w - Proxy password
    /help or /? - Lists the command list

    3.   Use CodeIt.Right Enterprise edition Team Configuration Module on another machine that has Visual Studio installed to create a custom CodeIt.Right profile.  Copy the profile to the TeamCity machine.  The profile can be found at:

            c:\Users\<user>\Documents\SubMain\CodeIt.Right Enterprise for VS20XX\Profiles\

    where VS20XX is the version of Visual Studio used to run the solution.

    Alternatively, you can use the Enterprise Edition profile publishing mechanism to sync the custom profile onto the TeamCity server.

    4.   Add the following code to *.target MSBuild:

    <UsingTask TaskName="CirBuildTask" AssemblyFile="$(ProgramFiles)\SubMain\CodeIt.Right Enterprise\SubMain.CodeItRight.MSBuild.dll" /> <Target Name="CodeItRight_CodeInspection">
    <CirBuildTask Solution="<solution file path>" OutputXmlFile="$(teamcity_build_checkoutDir)\SolutionViolations.xml" OutputHtmlFile="$(teamcity_build_checkoutDir)\SolutionViolations.html" ProfileName="Custom Profile 1" />
    </Target>

    where SolutionViolations.xml, SolutionViolations.html are output files, and Custom Profile 1 is the user profile you created in the previous step.

    5.   Create a Build Step in the project configuration.

    1_BuildStep 

    6.  In Project configuration -> General Settings -> Edit artifact paths add  “*.html”.

    2_GeneralSettings

    7.   Edit Project -> Reports Tab -> Create new report tab and confirm that Get Artifacts From contains "(last finished build)" and that Start Page contains "SolutionViolations.html". 

    3_ReportTabs

    8.   Run the project build and then select the CodeIt.Right Code inspection tab to see the violations report.

    4_ProjectOverview

    8.   Your violations report will look like this:

    5_AnalysisReport

    If you want to tweak the report layout visual appearance, you are able to do so by modifying XSLT stylesheet that is applied to the violation report XML output.

  • CodeIt.Right Check-In Policy Integration

    Using the Enterprise edition, CodeIt.Right integrates seamlessly into your Source Control procedures, letting you scan files, highlight issues or violations, and fix them before check-in.  Because you can test the code against any configured profile, you can be sure that it conforms to the team’s requirements before it’s allowed to be checked in. 

    Configuration

    First, select Team Project Settings –> Source Control… from the Team Explorer menu.

    Snap1

     

    The Source Control Settings dialog will appear.  Select the Check-in Policy tab and then click the Add button.

    Snap2

     

    When the list of available Check-in policies appears, select CodeIt.Right, then click OK.  (CodeIt.Right will register itself in Visual Studio when you install it.)

    Snap3

     

    The next dialog to appear will display all of your saved CodeIt.Right profiles.  This will include the built-in profiles together with any profiles you have created.

    Snap5

     

    Select the profile you want to have applied to this code before Check-in, then click OK.  Note that at this stage, you have the option to create a new profile or edit an existing one by using the buttons in that dialog. 

    Usage

    When you check-in your code, the Source Control Settings dialog shown below will appear.   This highlights the requirement for CodeIt.Right to be run before Check-in is allowed.  Note that again there are options to add, edit, remove, or disable this requirement.

    Snap6

     

    When you click OK to proceed, CodeIt.Right profile options will be displayed, allowing you to select a profile to apply.

    Snap7

     

    Once the profile has been selected, click OK to display the Check in – Source Files dialog.  Then, select the file(s) to be checked and click the Check In button. 

    Snap8

     

    CodeIt.Right will then run in the background, validating the code.  If violations are found, a warning message will be displayed.

    Snap9

     

    Double click on the description and CodeIt.Right will display a message that tells you that the violations list is ready to view.

    Snap90

     

    Click on the OK button to dismiss the dialog and bring the CodeIt.Right crdata file into view.  You can then fix the issues shown in the violations list, using the many options and features of CodeIt.Right.  Once the issues have been fixed, repeat the check-in procedure to check-in the corrected code file.

    This useful feature of the CodeIt.Right Enterprise Edition will help keep your team on track and ensure that only code that meets your required standards is allowed to be checked in.

  • Tutorial: How to access GhostDoc Pro key features

    Introduction

    Note: if you would like to get quick four minute overview of the key GhostDoc features before proceeding with the evaluation guide below, you can view this video.

    Once you've downloaded and installed GhostDoc Pro, you can access its features in several ways.

    First, it is added to the Tools menu in the Visual Studio IDE:

    1 Tools Menu

    Also, a new toolbar is added to the Visual Studio toolbars:

    2.GhostDocProToolbar

    And, as you'll see as the tutorial progresses, right-clicking inside a code file in the Code window of Visual Studio brings up a context menu of available GhostDoc Pro options.

    3 GhostDoc context menu

    The three key areas that will be covered in this introductory tutorial are shown below:

    4.Thethreekeyareas

    1. Documenting your code with XML comments

    2. Checking and fixing spelling errors

    3. Previewing formatted comments and building a complete Help file

    Although GhostDoc Pro offers much more than this, these are the features you'll most often use and are the ones where we believe GhostDoc Pro saves you the most effort.

    Documenting Code with XML Comments

    Document This

    You can create an initial set of XML comments in several ways.

    • Left-click on the code item for which you want to create comments.   Then, use the Ctrl+Shift+D hotkey combination to create the comment.
    • Left-click on the code item for which you want to create comments.  Then, click on the first button in the GhostDoc Pro toolbar.  Finally, select the Document This menu item. (See screenshot below).

    5.DocumentThisusingToolbar5

    • Right-click on the code item where you want to create comments.  Then, select GhostDoc Pro --> Document This from the context menu that appears.

    6.UseContextMenu1

    Whichever way you choose, the XML comment is automatically created. In this simple example, the result will be:

    7Initialcommentcreated 

    As you can see from the summary that's been automatically created in the example above, GhostDoc Pro can analyse the method name and produce an intelligent interpretation of what the method does. It will be most successful if you follow some basic naming rules:

    • Follow the Microsoft Naming Guidelines as far as possible (follow this link to view them)
    • In particular,
      • Use Pascal Casing or Camel Casing for identifier names
      • Start method names with a verb wherever possible
      • Avoid non-standard abbreviations – ReadXmlFile is OK; ClrMinVals is not.
    Re-Document This

    This Ghost Doc Pro feature (not available in the free version) lets you instantly update an existing XML comment if you've made a change to the code that will affect the comment.

    To implement this feature, left or right click on the code to be commented and then select the Re-Document This menu item. Alternatively, click on the small down arrow on the first button in the GhostDoc Pro toolbar. This will reveal the Document options menu, from which you can select Re-Document This:

    8ReDocumentThisfromToolbar

    In the simple example below, the original method name has been changed from GetPanelMeasurement to GetPanelMeasurements. When the Re-Document This feature is implemented, the summary element of the comment is automatically amended to reflect this change.

    8B.Originalcommentbeforeredocumentati[2]

    8A.Redocumentedcomment 

    Document Type

    Although best practice is to have only a single class in a code file, there may be times when you have to use code that doesn't follow this practice. In those cases, you can create comments for just one of the classes (GhostDoc Pro only). This is done by using the Document Type feature.

    To implement this feature, you select the code to be commented in one of the ways described above, and then select the Document Type menu item.

    9.Documentthistypeonly 

    Document File

    If you want to document the whole file in one pass, (only available in GhostDoc Pro), you select the Document File option from any of the three GhostDoc Pro menus described earlier.

    10DocumentFile

    Note that not only will this feature add XML comments for each member; it also creates a header for the file:

    11FileHeader 

    Spelling Checker

    Real-time spell checking

    GhostDoc Pro includes an intelligent spelling checker. You can enable the Spelling Checker feature either from the Tools --> GhostDoc Pro --> Enable Spell Checking option in Visual Studio, or by clicking the Enable Spell Checking option in the GhostDoc Pro toolbar (3rd button from the left).

    12 EnableSpellChecking

    Although using this Toolbar button is the easiest way to turn spell checking on or off, you do also have the option of using the GhostDoc main menu button, or right-clicking in the code pane and using the context menu.

    As soon as you activate this feature, real time spell checking will start and the current code page will be checked. Any potential spelling errors will be highlighted with a wavy line underneath the word.

    13 Configurtionexample1

    When you hover the cursor over the highlighted word, an options dialog will appear:

    14 Suggestedalternatives

    As you can see, as well as the standard feature of suggested alternative words, GhostDoc Pro lets you:

    • Manually type a replacement word (note that you must first left-click on the word you want to replace)
    • Add the highlighted word to the user dictionary. In this case, that word will be accepted in any solution the user opens in Visual Studio in the future.
    • Add the highlighted word to a dictionary for this Solution only.
    • Stop spell checking this file and ignore any future errors in the file.
    • Stop spell checking any file in the solution that has the same file extension.

    Ghost Doc Pro gives you very detailed control over what is spell checked and what is ignored.  To change the default settings, select Tools—>GhostDoc Pro—>Options.

    15 Spell check options

    Then, make your choices from the check boxes in the dialog box that appears:

    16 SpellingOptionsmenu

    You can choose to include or exclude:

    • Regular comments
    • String literals
    • Symbol names – i.e. Method names, Class members, etc.
    • XML comments
    • XML content
    • XML tags

    One particularly smart feature in the GhostDoc Pro Spell Checker is thee way it will split amalgamated words into their individual parts and check each part.

    In the following example, the words PartTimer and fullTime are both allowed because GhostDoc Pro has split them into ‘Part' and ‘Timer', and ‘full' and ‘Time' respectively, and all four of those words are spelled correctly.

    17 PartTimercasingexamples

    To show how this intelligent analysis works, the following version of the same code snippet will fail the spell check:

    18  spellcheckfailsonimpropercasing1

    As I mentioned previously, if you follow the guidelines for naming, this will greatly help you to create readable, understandable code that can be effectively commented and spell checked by GhostDoc.

    Bulk Spell Checking

    There are three options for bulk spell checking – Active Document, Current Project, and Entire Solution.

    If you want to spell check the active document, the quickest way is to click on the Check Spelling – Active Document button on the GhostDoc Pro toolbar (4th icon from the right).

    19  CheckSpellingActiveDocumentbutton

    All three options can be easily accessed by clicking the down arrow to the right of that button.

    20  BulkSpellCheckingOptionsonToolbar

    They can also be accessed from the Tools --> GhostDoc Pro menu in the Visual Studio IDE.

    These menu options are mostly self-explanatory. Whichever of the three options you choose, a Spelling Report will be generated and displayed:

    21  SpellingReport1

    This report displays the individual items picked up by the spell checker, grouped by file name, and listed with their line number in the code file.

    When you left-click on any item in this list, the code window will navigate to show you where that selected item is in the code:

    22  SpellingErrorinbothpanes

    You can edit the misspelt word in the code window as shown earlier, and you can also make the change in the Spelling Report. To do this, right-click on the item in the Spelling Report and when the error correction dialog appears, make the change you require. You will have the same list of options that you saw earlier. Any change you make will immediately be reflected in the code and that error will disappear from the list of errors in the Spelling Report.

    Show Spelling Report

    This option is available from the GhostDoc Pro toolbar or from the Tools --> GhostDoc Pro menu. When you select this option, a Spelling Report based on your most recent option selection will be displayed. That is, if you last selected the Check Spelling – Current Project option, the report will include all relevant files in the project. If your last selection was one of the other two options, the report will include the active document only or every relevant file in the solution, respectively.

    Previewing Comments and Building a Help File

    Preview Comments

    You can see what an individual XML comment will look like after it's been built as a page in a help file by selecting the Preview Comment feature from the main menu, the context menu or the GhostDoc Pro toolbar (second button from the left – circled in the screenshot below).

    23  PreviewCommentfromToolbar

    This feature is very useful, even with simple comments such as this one:-

    24  simplecommentincodefile

    This will produce the following output:-

    25  PreviewCommentSimpleExample

    But the Preview Comment feature really comes into its own when you have more detailed or lengthy comments, such as this one:-

    26   Complex comment in code file

    The output generated for this example will be:

    27  Complex Comment Preview 

     

    Build a Help File

    The Build Help File feature (only available in GhostDoc Pro) gives you several options for building a complete Help file for the solution. This feature is accessed by clicking the small down arrow to the right of the Preview comment button in the GhostDoc Pro Toolbar:

    28  BuildHelpFileToolbaroption

    Alternatively, you can access it from the Tools –->GhostDoc Pro menu in the Visual Studio IDE.

    29  BuildHelpFileMenuitem1

    When you select it, you're presented with the following dialog:

    30  BuildHelpFiledialog1

    As you can see from the screenshot above, you have choices for:

    • The output path
    • Up to four different formats for the compiled help file
    • The scope of members that will be included
    • The exclusion of projects you don't want to include in the help file

    You can also select the Additional Options link and choose to include header and/or footer text in the help pages.

    31  AdditionalHelpOptions1

    The following screenshot shows an example of a solution compiled as a CHM file:

    32  CompiledHelpFile

     

    Summary

    This introductory article only covers the features of GhostDoc Pro that you'll likely use most often. There are many more than those covered here.

    The core functions that document XML comments and the Ctrl-Shift-D hot keys are what GhostDoc is most famous for. But the additional features of the very smart spell check utility, together with comment preview and Help file building, make GhostDoc Pro a utility that's much more than a plain old comment creator.

    I hope that this article will help you see what an invaluable tool GhostDoc Pro can be and that it'll encourage you to download the free trial and try out its features for yourself. We're confident that it will quickly make you more productive and within a very short time of using it, will find GhostDoc Pro to have been one of your better decisions.

  • CodeIt.Right SuppressMessage Attribute Primer

    While CodeIt.Right comes with a great number of ways to ignore (exclude) violation, rule, file, project, etc, it also supports the SuppressMessage route. In this post you will find sample syntax for SuppressMessage attribute. You will find that CodeIt.Right supports all of the FxCop SuppressMessage variations and slightly enhances the attribute syntax.

    // excludes all violations of the Design category
    [SuppressMessage("SubMain.CodeItRight.Rules.Design", "")]
    
    // excludes violation by rule ID
    [SuppressMessage("SubMain.CodeItRight.Rules.Design", "DE00010")]
    
    // excludes violation by rule name
    [SuppressMessage("SubMain.CodeItRight.Rules.Design", "TypesContainStaticMembersShouldBeSealed")]
    
    // excludes violation by rule ID and rule name
    [SuppressMessage("SubMain.CodeItRight.Rules.Design", "DE00010:TypesContainStaticMembersShouldBeSealed")]
    
    // excludes TypesAndMembersShouldHaveXmlComments rule for the class and all its members 
    [SuppressMessage("SubMain.CodeItRight.Rules.General", "GE00005:TypesAndMembersShouldHaveXmlComments")]
    public class MyUndocumentedClass
    {
        public void MyUndocumentedMethod1{}
        public void MyUndocumentedMethod2{}
    }

    CodeIt.Right also supports the following syntax:

    [SuppressMessage("SubMain.CodeItRight.Rules.Naming", "IdentifiersShouldBeCasedCorrectly", Scope = "method")]

    Acceptable values for Scope include:

    • member
    • resource
    • module
    • type
    • method
    • namespace
    • method
    • member
    • parameter
    • type
    • namespace
    • module
    • statement
    • expression

    Using Target parameter:

    [SuppressMessage("SubMain.CodeItRight.Rules.Naming", "IdentifiersShouldBeCasedCorrectly",
    Scope = "method", Target = "Class1.Main(System.String[]):System.Void")] class Class1 { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { string fileIdentifier = name; string fileName = name; string version = String.Empty } }

    If you are using the Enterprise Edition of CodeIt.Right, you can also use GlobalSuppression.cs or GlobalSuppression.vb file:

    using System.Diagnostics.CodeAnalysis;
    
    [assembly:SuppressMessage("SubMain.CodeItRight.Rules.Naming", "IdentifiersShouldBeCasedCorrectly", 
    			Scope="method", Target="Class1.Main(System.String[]):System.Void")];
  • What does GhostDoc 'Document This' do?

    (This post is slightly edited version of the Introduction page in GhostDoc Help file)

    What does GhostDoc do?

    GhostDoc installs a new command - "Document This" into Visual Studio code editor context menu. When editing a source file, you simply navigate cursor into the language element you want to document (or in front of it, in the same text line), and call the "Document This" command by either pressing the hotkey you assigned to the command GhostDoc setup or using the context menu. GhostDoc analyses insert an XML documentation comment, much like typing "///" in front of a language element, but with a major difference: for specific language elements like methods and properties, GhostDoc attempts to generate large parts of the actual documentation (for other language elements like e.g. enums and their values, an empty summary will be generated).

    If a class member is an interface implementation or override of a base class member, GhostDoc will use the existing documentation, regardless of where the interface or base class comes from. So basically what this means that you can re-use tons of documentation that Microsoft wrote - just remember the last time you've implemented IEnumerable and thought about how to comment the GetEnumerator() method.

    In the cases where no existing documentation can be used, GhostDoc attempts to analyze the code element name. Under certain conditions (we'll get to that later) GhostDoc actually does very good job. Often enough the results are not accurate or even plain silly, but on average correcting the mistakes/problems in the generated documentation takes less time than writing the whole comment from scratch.

    But how can a tool with virtually no understanding of the English language generate often pretty accurate documentation? Well, the basic idea is pretty simple: GhostDoc assumes that your code follows Microsoft's Design Guidelines for Class Library Developers:

    • you are using PascalCasing or camelCasing to write identifier names consisting of multiple words
    • your method names usually start with a verb
    • you do not use abbreviations in identifier names

    If you follow these rules, for example, use "ClearCache()" instead of "Clrcch()", and choose more or less self-documenting identifier names, there's a good chance for GhostDoc to split the identifier names into words, tweak and/or shuffle the words a little and produce a comment that, while not being perfect, gives you a head start on the way to a good documentation.

    As already mentioned, GhostDoc does not really understand English identifier names, nevertheless it attempts to apply certain rules to increase the quality of the generated comments:

    • Handling of verbs (GhostDoc assumes the first word of a method name is a verb): Add -> Adds, Do -> Does, Specify –> Specifies
    • "Of the" reordering (using trigger words like "width", "height", "name", etc.): ColumnWidth -> Width of the column
    • Combined with special handling of specific prefix words: MaximumColumnWidth -> "Maximum width of the column" instead of "Width of the maximum column"
    • Automatic detection of acronyms consisting of consonants (Html -> HTML), combined with a list-based approach for other acronyms (Gui –> GUI)
    • Use of a list of words where that should not be headed by a "the" (AddItem -> Adds the item, but BuildFromScratch -> Builds from scratch)

    Here's example of what GhostDoc is able to do: If you a method "DetermineInputCacheSize", GhostDoc will create the summary "Determines the size of the input cache." If you want to see more examples, take a look at the demo project.

    Since the quality of the comment depends on the identifier name and its structure, using GhostDoc for a longer period of time actually teaches writing consistent and self-documenting identifier names, which is definitely a nice added bonus.

    What doesn't GhostDoc do?

    GhostDoc cannot do miracles, and the way it generates documentation may not work well with your personal style. If you are not following the Microsoft Guidelines, you will most likely run into problems.

    When GhostDoc is able to re-use documentation from interfaces and base class members, it simply copies the comments over. It does not check whether the comment still applies, which, for example, becomes obvious when you document an override of the ToString method of System.Object. The generated summary is "Returns a System.String that represents the current System.Object." (<see> tags omitted for clarity), where it should read "Returns a System.String that represents the current MyNamespace.MyClass.". A developer quickly figures out that in this case, System.Object has to be replaced, but a tool like GhostDoc cannot (at least not without an extensive code analysis).

    Intentionally, GhostDoc is not a tool for creating the complete documentation for a given source file in one go. You can only document one member at a time, because you always have to check and extent the results of each auto-generated comment to make it clear and actually useful.

    What is GhostDoc Pro?

    GhostDoc Pro is an enhanced version of the product that gives you complete control over your XML Comment content and layout as well as automates XML Comment generation via batch actions.

    The Pro version has all features of GhostDoc and adds:

    • T4 based XML Comment templates - total control over your XML documentation content and style
    • Document Type - generates XML comments for entire type/class
    • Document File - generates XML comments for entire file
    • Source code Spell Checking
    • XML Comment Preview
    • Generate XML Comment based Help Documentation
    • StyleCop compliant comments
    • Exception Documentation 

     

  • How CodeIt.Right is better than FxCop?

    The biggest benefit of CodeIt.Right is the automatic code correction and refactoring to patterns. The alternative is you could manually spend hours or even days on some pesky violations rather CodeIt.Right do the work for you in a matter of minutes.

    You can also choose to follow Microsoft Guidelines or you own custom standards, group rule sets into profiles, generate your custom standard documentation, efficiently work with existing/legacy projects, avoid false positives.

    The Enterprise Edition adds Team features, Code Metrics, Statistics, enhanced reporting.

      CodeIt.Right FxCop
    Instant Code Review Real-time code analysis provides instant feedback to developers in the Visual Studio Editor and fixes issues on the spot N/A
      Scans and analyzes source code Runs on compiled assemblies (you have to compile code to use it)
    Correction Corrects violations and code smells automatically  N/A
    Refactoring to patterns Automatically implements and corrects most common coding patterns like Dispose/Finalize, ISerializable, Custom Serialization, etc  N/A
    Visual Studio Integration Natively integrates into Visual Studio IDE; quick navigation to the violation source code; highlights modifications in the editor; safe Undo/Redo. Basic/Command line
    ASP.NET ASPX/ASCX/ASMX pages, in-page code, code behind source Only compiled code behind assemblies
    Local variables/constants Includes rules that are targeting local variables/constants and any data that is present in the source code Not possible in FxCop - the data is lost in the MSIL
    Follow your own standards Includes Microsoft Guidelines and best industry practices out of the box. Allows to define your own standard to follow - tweak the rule set to your needs without having to write custom rules (which is an option too). For example, go as crazy as enforce Hungarian naming conventions; or convert existing project with Hungarian notation to the new MS style conventions. Strictly enforces Microsoft Guidelines - inflexible and enforces the set with no options to configure
    Define custom rule set Profiles - configure multiple rule subsets and quickly switch between them. Share profiles between the Team members or (EE) push them to the Team.  N/A
    Rule Instances Introduces Rule Instances - multiple instances of a single rule that are configured (via rule Properties) to your Team needs Only allows to turn off specific rule, cannot configure/tweak
    Reducing noise (false positives)
    • Exclude violation in Project
    • Exclude violation in source code
    • Exclude Violation, Rule, File, Project
    • Exclude code regions
    • Custom Profiles
    • Override default rule severity, target, scope, etc
    • Exclude violation in Project
    • Exclude violation in source code
    Severity Threshold Unique feature - Severity Threshold - allows to concentrate on most critical violations first and drill down from most severe issues to simple warnings.  N/A

    Scan entire solution, project, folder or individual file Scan projects only
    Create own guidelines documentation Generate Team Guidelines document within a mouse click, with description, code samples, etc - based on your custom configured Profile  N/A
    Team features (EE) separate modules to (a) author / configure team standards and (b) run analysis and correction based on the team standard configured by Team Lead/Architect; publish and push (share) Team standard configuration to the Team members; Team usage statistics  N/A
    Reporting Flexible reporting/pivot that can be exported and printed  N/A
    Code Metrics Available (EE); can be exported, printed, emailed  N/A
    Command line output Violations, Code Metrics (EE) Violations only
    Command line filtering Solution, Project, Profile, Severity Threshold Project, Assembly
    Command line delivery File, Send via email File only
    Command line integration Command line tool, MsBuild and NAnt tasks Command line tool
    Update delivery Rule Library auto-update - get new rules when we publish them
     N/A

    Download trial copy of CodeIt.Right today and see the difference yourself!

     

  • XML Comment template: IntelliComment or XML Comment Stub?

    One of the very helpful and important rules that we added in the past few months is the one that finds members that missing XML documents when these are required - General / Type, Member -> Should have XML comments (Externally visible types and members should have XML comments).

    One of the most frequently asked question about the rule is why some users are not seeing the missing XML comment violation on select project. There are two possible reasons for that:

    1. The rule will only trigger violation on public and protected members in its default configuration. If you choose to have it validate private and/or static members, you will need to edit the rule's Scope property to include those as well.
    2. The option to generate XML documentation is turned OFF in  your project. In this case the rule doesn't the missing XML comment violation to reduce false positives since the project setting state it does not need XML documentation.

    To turn the option to generate documentation ON, in C# project, go to project Properties -> Build -> XML documentation file

    XMLComment1

    In VB project, go to project Properties -> Compile -> Generate XML documentation file

    XMLComment2

    In the spirit of CodeIt.Right the rule offers two automatic correction options - IntelliComment and XML Comment Stub. In the default configuration these are fairly similar, the difference is that IntelliComment will fill in the generated XML Comment using data from our GhostDoc engine, while the Stub template will create an empty XML Comment Stub.

    Here is example generated by IntelliComment template

        /// <summary>
        /// Determines the size of the page buffer.
        /// </summary>
        /// <param name="initialPageBufferSize">Initial size of the page buffer.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public int DeterminePageBufferSize(
                               int initialPageBufferSize) {
    
            // Implement the method here
            return 1;
    
        }

    And example generated by XML Comment Stub template

        /// <summary>
        ///  
        /// </summary>
        /// <param name="initialPageBufferSize"> </param>
        /// <returns></returns>
        /// <remarks></remarks>
        public int DeterminePageBufferSize(
                               int initialPageBufferSize) {
    
            // Implement the method here
            return 1;
    
        }

    So, the rule offers two correction option - it is up to you to pick which template works best for your project.

    I notice that I keep using the word "template" when describing the two correction options. That is because these are true T4 templates that you can customize to fit your team requirements.

    Here is default IntelliComment template:

    <#@ template language="C#" #>
    <#
        CodeElement codeElement = Context.CurrentCodeElement;
    #>
    /// <summary>
    /// <#= codeElement.XmlComment.SummaryTagText #>    
    /// </summary>
    <#
        if(codeElement.HasTypeParameters) 
        {
            foreach(TypeParameter typeParameter in codeElement.TypeParameters) {
    #>
    /// <typeparam name="<#= typeParameter.Name #>"><#= typeParameter.XmlComment.TypeParamTagText #></typeparam>
    <#
            }
        }
        
        if(codeElement.HasParameters) 
        {
            foreach(Parameter parameter in codeElement.Parameters) {
    #>
    /// <param name="<#= parameter.Name #>"><#= parameter.XmlComment.ParaTagText #></param>
    <#
            }
        }
        
        if(codeElement.HasReturnType) {
    #>
    /// <returns><#= codeElement.XmlComment.ReturnsTagText #></returns>
    <#
        }
        
        if(codeElement.IsProperty) {
    #>
    /// <value><#= codeElement.XmlComment.ValueTagText #></value>
    <#
        }    
        
        if(codeElement.IsMember) {
    #>
    /// <remarks></remarks>
    <#
        }    
    #>

    As you can see it is very much self-explanatory and you can customize it to your needs. For example, in combination with the CodeIt.Right Global Properties feature, we can have <reviewed/> and <copyright/> data automatically when we add the following at the very end of the template:

    /// <reviewed><#= Context.GetGlobalProperty("UserName") #></reviewed>
    /// <copyright><#= Context.GetGlobalProperty("CompanyName") #> Copyright <#= System.DateTime.Now.Year.ToString() #></copyright>

    Pretty powerful stuff, huh?

  • Tutorial: Extending Existing Rules

    You already know how you can create new custom rules using CodeIt.Right SDK, of not, you may want to read this article first.

    In this tutorial we will show how to extend existing rules using the new SDK features introduced in CodeIt.Right v1.8.09300. The new technique is to derive the custom rule from a base rule and override only the methods that need to be modified.

    Let's extend the rule "Avoid single line If statement" (RuleID: CD0002; base class AvoidSingleLineIfStatement) in the Coding Style category:

    ExtendingRules1

     

    The base rule above will trigger a violation when find a code pattern like this:

    if (x > 0) y = 0;

    When the rule default correction action "Split If block into a multiline statement" is used it will modify the code into:

     

    if (x > 0)
    {
        y = 0;
    }

    That is what comes in the box.

    Our team may have an internal guideline that requires a single line conditional to be split into two lines without the squiggly brackets:

    if (x > 0)
        y = 0;

     

    Hey, not all teams are created equal :)

    In this case correction option that comes with the base rule AvoidSingleLineIfStatement is not very useful and we need to extend the rule with our custom correction.

    So, let's start.

    We will skip the list of required referenced  assemblies - you will find them in the complete code sample at the end of the post.

    Declare new class that inherits from the base rule class:

    namespace CustomRuleLibrary.CodingStyle 

        [Serializable] 
        [ModificationDate("10/14/2009")] 
        [Category("CustomRuleLibrary.CodingStyle")] 
        public class AvoidSingleLineIfStatement2 : AvoidSingleLineIfStatement   // Must reference SubMain.CodeItRight.Rules.CodingStyle.dll for this  
        {

    In the code above we also set the Category attribute to "CustomRuleLibrary.CodingStyle" so we could easier find the custom in the Profile.

    We override ID property and use GUID for the new RuleID value. Some of the CodeIt.Right functions, for example, help pages are handled differently for custom rules. Using GUID for RuleID hits CodeIt.Right that the rule is custom.

            public override string ID 
            { 
                get 
                {  
                    // Override the RuleID value with own GUID (recommended)
                    return "6C832235-0B02-4227-911A-156F0B1FAC71"
                } 
            } 

    Property AutoCorrectionOptions needs to be overridden to add new correction action "Split If block into a multiline statement without block":

            /// <summary>
            /// Returns list of auto correction options 
            /// </summary>
            public override string[] AutoCorrectionOptions 
            { 
                get 
                { 
                    IMethodInfo methodInfo = Element as IMethodInfo; 
                    if (methodInfo != null
                    { 
                        // Get the base class list of available corrections
                        string[] baseOptions = base.AutoCorrectionOptions; 
                        string[] options = (string[])Array.CreateInstance(typeof(string), baseOptions.Length + 1); 
                        // Add new correction action to the list
                        Array.Copy(baseOptions, 0, options, 0, baseOptions.Length); 
                        options[options.Length - 1] = "Split \"If\" block into a multiline statement without block"

                        return options; 
                    } 

                    return new string[] { }; 
                } 
            }

    The base rule correction option:

    ExtendingRules2

    Our custom rule correction options with the new action added in the AutoCorrectionOptions above:

    ExtendingRules3

    Now we implement our new custom correction action just the way we like it to work:

            /// <summary>
            /// Implementation of our custom correction action 
            /// </summary>
            private bool Correct_1(IElementInfo elementInfo) 
            { 
                IMethodInfo methodInfo = Element as IMethodInfo; 
                if (methodInfo != null
                { 
                    StatementCollection statements = RuleUtilities.GetMethodStatements(methodInfo); 
                    IStatement statement = SearchForSingleLineIfStatement(statements); 
                    if (statement != null
                    { 
                        string codeToInsertAfter = Environment.NewLine; 
                        string codeToInsertBefore = Environment.NewLine; 

                        IRegion ifBlockRegion = GetIfBlockRegion(statement); 
                        if (ifBlockRegion != null
                        { 
                            string ifBlockText = GetIfBlockText(statement, ifBlockRegion); 
                            if (ifBlockText != null
                            { 
                                methodInfo.ReplaceCodeBlock(ifBlockRegion, 
                                    codeToInsertBefore + ifBlockText + codeToInsertAfter); 

                                return true
                            } 
                        } 
                    } 
                } 

                return false
            }

    And we tie it all together in the method Correct - for correction action with index 0 we execute the base rule correction and for the index 1 (that we added) execute method Correct_1 that implements our custom correction:

            /// <summary>
            /// Execute the specified correction action 
            /// </summary>
            /// <param name="correctionOptionIndex">Index of the correction action</param>
            public override bool Correct(int correctionOptionIndex) 
            { 
                bool result = base.Correct(correctionOptionIndex); 

                switch (correctionOptionIndex) 
                { 
                    case 0
                        // For correction action 0 execute the base class correction
                        return result; 
                    case 1
                        // For correction action 1 execute our custom correction
                        return Correct_1(Element); 

                    default
                        break
                } 

                return false
            }

    And we are done!

    The final steps are to compile the new rule, drop the assembly to Program Files\SubMain\CodeIt.Right\Rules\ and we can now add the rule to a profile:

    ExtendingRules4

    Here is the complete code for our custom rule:

    using System;
    using System.IO;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Runtime.Serialization;
    using System.Globalization;

    using SubMain.CodeObjectModel.Reflection;
    using SubMain.Core.Services;
    using SubMain.CodeItRight.Sdk;
    using SubMain.CodeItRight.Sdk.Core.Collections;
    using SubMain.CodeItRight.Sdk.Core.Reflection;
    using SubMain.CodeItRight.Sdk.Core.Rules;
    using SubMain.CodeItRight.Sdk.Core.Utils;
    using SubMain.CodeItRight.Sdk.Rules;
    using SubMain.CodeItRight.Sdk.Utils;
    using SubMain.CodeItRight.Rules.CodingStyle;

    namespace CustomRuleLibrary.CodingStyle
    {
        [Serializable]
        [ModificationDate("10/14/2009")]
        [Category("CustomRuleLibrary.CodingStyle")]
        public class AvoidSingleLineIfStatement2 : AvoidSingleLineIfStatement   // Must reference SubMain.CodeItRight.Rules.CodingStyle.dll for this
        {
            /// <summary>
            /// Returns list of auto correction options
            /// </summary>
            public override string[] AutoCorrectionOptions
            {
                get
                {
                    IMethodInfo methodInfo = Element as IMethodInfo;
                    if (methodInfo != null)
                    {
                        // Get the base class list of available corrections
                        string[] baseOptions = base.AutoCorrectionOptions;
                        string[] options = (string[])Array.CreateInstance(typeof(string), baseOptions.Length + 1);
                        // Add new correction action to the list
                        Array.Copy(baseOptions, 0, options, 0, baseOptions.Length);
                        options[options.Length - 1] = "Split \"If\" block into a multiline statement without block";

                        return options;
                    }

                    return new string[] { };
                }
            }

            /// <summary>
            /// Implementation of our custom correction action 
            /// </summary>
            private bool Correct_1(IElementInfo elementInfo)
            {
                IMethodInfo methodInfo = Element as IMethodInfo;
                if (methodInfo != null)
                {
                    StatementCollection statements = RuleUtilities.GetMethodStatements(methodInfo);
                    IStatement statement = SearchForSingleLineIfStatement(statements);
                    if (statement != null)
                    {
                        string codeToInsertAfter = Environment.NewLine;
                        string codeToInsertBefore = Environment.NewLine;

                        IRegion ifBlockRegion = GetIfBlockRegion(statement);
                        if (ifBlockRegion != null)
                        {
                            string ifBlockText = GetIfBlockText(statement, ifBlockRegion);
                            if (ifBlockText != null)
                            {
                                methodInfo.ReplaceCodeBlock(ifBlockRegion,
                                    codeToInsertBefore + ifBlockText + codeToInsertAfter);

                                return true;
                            }
                        }
                    }
                }

                return false;
            }

            public override string ID
            {
                get
                { 
                    // Override the RuleID value with own GUID (recommended)
                    return "6C832235-0B02-4227-911A-156F0B1FAC71";
                }
            } 

            /// <summary>
            /// Execute the specified correction action
            /// </summary>
            /// <param name="correctionOptionIndex">Index of the correction action</param>
            public override bool Correct(int correctionOptionIndex)
            {
                bool result = base.Correct(correctionOptionIndex);

                switch (correctionOptionIndex)
                {
                    case 0:
                        // For correction action 0 execute the base class correction
                        return result;
                    case 1:
                        // For correction action 1 execute our custom correction
                        return Correct_1(Element);

                    default:
                        break;
                }

                return false;
            }

        }
    }

    Further Reading and Resources

  • CodeItRight.Cmd.exe Command Line Options

    CodeItRight.Cmd is the command-line companion to the CodeIt.Right application. Like CodeIt.Right, CodeItRight.Cmd analyzes source code and reports violations, such as possible design, performance, and security issues. CodeItRight.Cmd can be used as a stand-alone tool or added to automated build processes.

    The following are the command line parameters that are supported by SubMain.CodeItRight.Cmd.exe ; Parameter values are not case sensitive.

    /Solution  - (Required*) - full file name of the solution to load (*.sln file) (*) This parameter is not required if /Project parameter specified.
     
    /Project   - (Required*) - full file name of the project to load (*.csproj or *.vbproj file) (*) This parameter is not required if /Solution parameter specified.

    /Out  - (Required) - full name of the XML report output file.

    /OutXSL  - (Optional) - full name of the XSL file to override the default xsl.

    /OutHtml  - (Optional) – specifies the full name of the HTML report output file when the HTML format preferred over the default XML.

    /CRData - (Optional) - full name of the CodeIt.Right .crdata file. When specified, CodeItRight.Cmd will use the exclusion list (violations, rules and files) saved using the Visual Studio version of CodeIt.Right.

    /Profile  - (Optional) - name of the User Profile that defines active rule set for the analysis. When omitted, the built-in profile is used. The parameter value is not absolute path but rather profile name as you see it in the dropdown in Visual Studio toolbar. Note: CodeItRight.Cmd is looking for the profile <USER>\Documents\SubMain\CodeIt.Right {Edition} for VSxxxx\Profiles – when running CodeItRight.Cmd under a different user, be sure to copy your profiles into the corresponding folder for that user.

    /severityThreshold  - (Optional) - Severity Threshold value to limit the output violation set. When omitted, the the lowest Severity is used - None. Accepted values (from Higher to Lower):

    • CriticalError
    • Error
    • CriticalWarning
    • Warning
    • Information
    • None

    /ProjectConfiguration - (Optional) – specifies one of the project configurations in Visual Studio - typically Debug or Release but this also allows to use your custom configuration if you created it your VS environment. Sample syntax for /ProjectConfiguration parameter:

        /ProjectConfiguration:"Release"

    /RunStyleCop - (Optional) – runs StyleCop ruleset analysis when StyleCop is integrated with CodeIt.Right. Sample syntax for /RUnStyleCop parameter:

        /RunStyleCop

    /DateAfter - (Optional)(v3 Only) – analyze only files modified after the the date (yyyy-MM-dd) – works only in v3 or newer. Sample syntax for /DateAfter parameter:

        /DateAfter:"2012-02-16"

    /UseAnalyzeList - (Optional)(v3 Only) – analyze only files provided in <AnalyzeList /> of the .CRDATA file – works only in v3 or newer. Sample syntax for /UseAnalyzeList parameter:

        /UseAnalyzeList

    /Quiet - (Optional) - disables console output.
     
    /Help  - display list of command line parameters.

    Example:

    SubMain.CodeItRight.Cmd.exe /Solution:"C:\MyProjects\MyProject\MyProject.sln"
    /Out:"C:\MyProjects\MyProject\MyProject.CIR.Output.xml"
    /CRData:"C:\MyProjects\MyProject\MyProject.crdata" /Profile:"My Profile" /severityThreshold:"Error"

    Enterprise Edition Enhancements

    The Enterprise Edition extends command line parameters to enable code metrics output and report distribution over email.

    /RuleUpdate - (Optional)(EE Only) - this switch allows to propagate profile and rule changes published into Shared Folder. This is to be used in a build server Cmd only (no Visual Studio) setup.

    /PropertyFilePath - (Optional)(EE Only) – allows pointing to a CodeIt.Right settings file to use one a shared location or for any reason to use the settings file alternative to the one in the user Documents folder. Sample syntax for /PropertyFilePath parameter:

        /PropertyFilePath:"\\networkshare\CodeIt.Right\TeamConfiguration\CodeIt.Right.Properties.xml"

    /Metrics - (Optional)(EE Only) - generates XML output for one of the three code metrics reports – "Member", "Type" and "Code". Sample syntax for /Metrics parameter:

        /Metrics:"Member"
    or
        /Metrics:"Type"
    or
        /Metrics:"Code"

    /SendTo - (Optional)(EE Only) - sends violation/metrics reports to list of email addresses. Sample syntax for /SendTo parameter:

    /SendTo:"email1@gmail.com;email2@gmail.com"

    Mail server is configured in "<Documents>\SubMain\CodeIt.Right Enterprise for VSxxxx\Properties\CodeIt.Right.Properties.xml"

    <Property PropertyID="3" Name="SmtpServer" Value="mail.server.com" />
    <Property PropertyID="4" Name="SmtpPort" Value="25" />
    <Property PropertyID="5" Name="SmtpEnableSsl" Value="false" />
    <Property PropertyID="6" Name="SmtpUserName" Value="" />
    <Property PropertyID="7" Name="SmtpPassword" Value="" />
    <Property PropertyID="8" Name="MailSubjectPrefix" Value="" />
    <Property PropertyID="9" Name="MailFrom" Value="user@server.com" />

    /mailSubject - (Optional)(EE Only) – overrides the default email subject - only applies when the SendTo parameter is specified. Sample syntax for /mailSubject parameter:

    /mailSubject:"Violations report for MySolution.sln with Security Ruleset"

    CodeItRight.Cmd Error Codes

    Returns

    • Positive code equal to the number of violations found
    • 0 - No violations and no errors found
    • Negative codes for internal errors:
    -1 Command Line Switch Error
    -2 Command Line Argument Error
    -3 Initialization Error
    -4 Analysis Error
    -5 Output Error
    -6 Unknown Error
More Posts Next page »
    
 
     
 
Home |  Products |  Services |  Download |  Purchase |  Support |  Community |  About Us |