<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Dr. Random - CodeRush</title>
    <link>http://www.drrandom.org/</link>
    <description>Random Thoughts for Random People</description>
    <language>en-us</language>
    <copyright>Casey Kramer</copyright>
    <lastBuildDate>Tue, 15 Dec 2009 15:08:44 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>casey.kramer@gmail.com</managingEditor>
    <webMaster>casey.kramer@gmail.com</webMaster>
    <item>
      <trackback:ping>http://www.drrandom.org/Trackback.aspx?guid=49ad68e1-3159-4225-ab35-8c1a345429da</trackback:ping>
      <pingback:server>http://www.drrandom.org/pingback.aspx</pingback:server>
      <pingback:target>http://www.drrandom.org/PermaLink,guid,49ad68e1-3159-4225-ab35-8c1a345429da.aspx</pingback:target>
      <dc:creator>Casey Kramer</dc:creator>
      <wfw:comment>http://www.drrandom.org/CommentView,guid,49ad68e1-3159-4225-ab35-8c1a345429da.aspx</wfw:comment>
      <wfw:commentRss>http://www.drrandom.org/SyndicationService.asmx/GetEntryCommentsRss?guid=49ad68e1-3159-4225-ab35-8c1a345429da</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
On November 27th, a beta release of the 9.3 version of the Developer Express components,
including CodeRush and Refactor Pro! was made available to subscribers.  This
release is pretty significant to me because it contains a major feature that I have
been waiting for <a href="http://www.drrandom.org/2007/07/13/TakingTheCodeRushPlunge.aspx" target="_blank">for
a long time</a>: A Unit Test Runner.  There were some teasers released by <a href="http://community.devexpress.com/blogs/markmiller/">Mark
Miller</a> a while back, which only made me want to get my hands on the tool that
much more.  My initial impressions are that it is very nice.  It is similar
to <a href="http://www.testdriven.net">TestDriven.Net</a> in that it provides context
menu options to run tests at various levels of granularity (single test, file, project,
and solution level) and includes a debug option.  At this point it does not contain
some of the additional coolness that TestDriven gives you like NCover/Team Coverage
and TypeMock integration, but it does have the advantage of being extensible. 
I know it was extensible because Mr. Miller <a href="http://community.devexpress.com/blogs/markmiller/archive/2009/11/16/the-test-runner-you-ve-been-waiting-for.aspx">told
me it was extensible</a> (the title “The Extensible Unit Test Runner You’ve Been Waiting
For” was a clue).  I did not realize how extensible, however, until after I submitted
a <a href="http://www.devexpress.com/issue=B142663">bug report</a> to DevExpress. 
The bug I was reporting (the NUnit TestCase attributes were not recognized), it turns
out, was already brought to the attention of the DX team by way of a <a href="http://community.devexpress.com/forums/p/83453/285881.aspx#285881">forum
post</a>, and they had already planned on correcting it with the next 9.3 release,
but I could have saved myself (and Vito on DevExpress team) some time by taking a
peek at the source samples bundled with the 9.3 release.  Yep, you guessed it,
there with a shared source license were all of the test framework implementation projects. 
So this meant I could whip together my own temporary fix while I was waiting for the
next release.  It seemed like something that other folks might want to know about,
so I thought I would share it here.
</p>
        <p>
The biggest piece of the puzzle is a new TestExecuteTask class for handling the TestCaseAttribute. 
Due to my complete lack of creativity, I called mine TestCaseExecuteTask, and it looks
like this: 
</p>
        <pre class="brush: csharp" name="code">using System;
using System.Collections.Generic;
using System.Text;
using DevExpress.CodeRush.Core.Testing;
using System.Reflection;
using DevExpress.CodeRush.Core;

namespace CR_NUnitTesting
{
    public class TestCaseExecuteTask : TestExecuteTask
    {
        public override TaskExecuteResult CollectTestParameters()
        {
            TaskExecuteResult result = TaskExecuteResult.SkippedTaskResult;
            Attribute testCase = GetMethodAttribute("NUnit.Framework.TestCaseAttribute");
            if (testCase == null)
                return result;
            
            foreach(Attribute testCaseItem in TestMethod.GetCustomAttributes(true))
            {
                if(testCaseItem == null)
                    continue;
                var testCaseType = testCaseItem.GetType();
                if(testCaseType == null || testCaseType.FullName != "NUnit.Framework.TestCaseAttribute")
                    continue;
                PropertyInfo prop = testCaseType.GetProperty("Arguments");
                if(prop == null)
                    continue;
                foreach(MethodInfo getter in prop.GetAccessors())
                {
                    object[] parameters = getter.Invoke(testCaseItem, Type.EmptyTypes) as object[];
                    result.AddParameters(parameters);
                }
            }
        }
    }
}
</pre>
        <p>
This could be cleaned up some, and some of the magic strings extracted to constants,
but overall it is pretty simple. Basically what is going on here is that we are looking
for the TestCase attribute, and extracting the arguments for any attributes we find. 
It just so happens that the TestExecuteTask base class has a CollectTestParameters()
method we can override which allows for this sort of Row testing.  The parameters
we extract get stashed in the execution result, which causes the test runner to execute
the test once for each group of parameters (the result has a list of parameters, which
gets populated with an array of objects for each TestCase attribute), and will correctly
display which cases failed if there is a failure.
</p>
        <p>
There are a couple other small changes that need to happen to get this to work. 
There is an NUnitExtension.cs  class, which is the Plug-In class for the NUnit
support, and it handles wiring everything up for us.  First off we need to initialize
our new TestExecuteTask, and add it to the list of tasks that run for NUnit tests. 
We do that in the InitializePlugin method of the NUnitExtension class: 
</p>
        <pre class="brush: csharp">public override void InitializePlugin()
{
    base.InitializePlugin();
    nUnitProvider.AvailableTasks.Add(new NUnitIgnoreTask());
    nUnitProvider.AvailableTasks.Add(new NUnitSetupTearDownTask());
    nUnitProvider.AvailableTasks.Add(new NUnitExpectedExceptionTask());
    nUnitProvider.AvailableTasks.Add(new NUnitValuesTask());
    nUnitProvider.AvailableTasks.Add(new NUnitRowTestTask());
    nUnitProvider.AvailableTasks.Add(new NUnitTimeoutTask());
    nUnitProvider.AvailableTasks.Add(new NUnitExplicitTask());
    nUnitProvider.AvailableTasks.Add(new NUnitTestCaseTask());
}
</pre>Ours
gets added to the end of the list, so it will be executed. The next step is to get
the plug-in to realize that a method with a TestCase attribute is an executable test
method. That trick happens in the handler for the CheckTestMethod event on the UnitTestProvider.
All we're going to do is add another condition to an if statement like so: <pre class="brush: csharp">void nUnitProvider_CheckTestMethod(object sender, CheckTestMethodEventArgs ea)
{
    IMethodElement method = ea.Method;
    if(//method.Name != null &amp;&amp; method.Name.StartsWith("Test")
       ea.GetAttribute("NUnit.Framework", "Test", method) != null
    || ea.GetAttribute("NUnit.Framework.Extensions", "RowTest", method) != null
    || ea.GetAttribute("NUnit.Framework", "TestCase", method) != null)
    {
        ea.IsTestMethod = true;
        ea.Description = ea.GetAttributeText("NUnit.Framework", "Description", method);
        ea.Category = ea.GetAttributeText("NUnit.Framework", "Category", method);
    }
}
</pre><p>
The only change to the original code was the additional GetAttribute call at the end
of the if statement (the comments were there when I got there, I swear).  Now
the only thing left to do is to compile it and drop it in the plug-ins directory. 
Now when you are looking at a test class, you should be able to run TestCase decorated
test methods without problem.  Well, almost.  There is one thing I was not
able to find a clean way to implement, and that is the Result property of the TestCase
attribute.  This allows you to streamline tests which are doing equals assertions
by having the test method return the actual result, and you specify the expected result
by using the result property.  Unfortunately I could not find a way to hook into
the actual execution of the test in such a way that I could have access to the specific
test properties being used, and the result of the test method execution.  But
considering the DevExpress folks will be fixing this issue, I’m sure when they release
it there will be support for this feature.  After all, this is simply a stop-gap
solution until the next CodeRush release is available, so I’m willing to live with
this slight inconvenience.
</p><p>
Happy Testing!   
</p><img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=49ad68e1-3159-4225-ab35-8c1a345429da" /></body>
      <title>More CodeRush Awesomeness</title>
      <guid isPermaLink="false">http://www.drrandom.org/PermaLink,guid,49ad68e1-3159-4225-ab35-8c1a345429da.aspx</guid>
      <link>http://www.drrandom.org/2009/12/15/MoreCodeRushAwesomeness.aspx</link>
      <pubDate>Tue, 15 Dec 2009 15:08:44 GMT</pubDate>
      <description>&lt;p&gt;
On November 27th, a beta release of the 9.3 version of the Developer Express components,
including CodeRush and Refactor Pro! was made available to subscribers.&amp;nbsp; This
release is pretty significant to me because it contains a major feature that I have
been waiting for &lt;a href="http://www.drrandom.org/2007/07/13/TakingTheCodeRushPlunge.aspx" target="_blank"&gt;for
a long time&lt;/a&gt;: A Unit Test Runner.&amp;nbsp; There were some teasers released by &lt;a href="http://community.devexpress.com/blogs/markmiller/"&gt;Mark
Miller&lt;/a&gt; a while back, which only made me want to get my hands on the tool that
much more.&amp;nbsp; My initial impressions are that it is very nice.&amp;nbsp; It is similar
to &lt;a href="http://www.testdriven.net"&gt;TestDriven.Net&lt;/a&gt; in that it provides context
menu options to run tests at various levels of granularity (single test, file, project,
and solution level) and includes a debug option.&amp;nbsp; At this point it does not contain
some of the additional coolness that TestDriven gives you like NCover/Team Coverage
and TypeMock integration, but it does have the advantage of being extensible.&amp;nbsp;
I know it was extensible because Mr. Miller &lt;a href="http://community.devexpress.com/blogs/markmiller/archive/2009/11/16/the-test-runner-you-ve-been-waiting-for.aspx"&gt;told
me it was extensible&lt;/a&gt; (the title “The Extensible Unit Test Runner You’ve Been Waiting
For” was a clue).&amp;nbsp; I did not realize how extensible, however, until after I submitted
a &lt;a href="http://www.devexpress.com/issue=B142663"&gt;bug report&lt;/a&gt; to DevExpress.&amp;nbsp;
The bug I was reporting (the NUnit TestCase attributes were not recognized), it turns
out, was already brought to the attention of the DX team by way of a &lt;a href="http://community.devexpress.com/forums/p/83453/285881.aspx#285881"&gt;forum
post&lt;/a&gt;, and they had already planned on correcting it with the next 9.3 release,
but I could have saved myself (and Vito on DevExpress team) some time by taking a
peek at the source samples bundled with the 9.3 release.&amp;nbsp; Yep, you guessed it,
there with a shared source license were all of the test framework implementation projects.&amp;nbsp;
So this meant I could whip together my own temporary fix while I was waiting for the
next release.&amp;nbsp; It seemed like something that other folks might want to know about,
so I thought I would share it here.
&lt;/p&gt;
&lt;p&gt;
The biggest piece of the puzzle is a new TestExecuteTask class for handling the TestCaseAttribute.&amp;nbsp;
Due to my complete lack of creativity, I called mine TestCaseExecuteTask, and it looks
like this: &lt;pre class="brush: csharp" name="code"&gt;using System;
using System.Collections.Generic;
using System.Text;
using DevExpress.CodeRush.Core.Testing;
using System.Reflection;
using DevExpress.CodeRush.Core;

namespace CR_NUnitTesting
{
    public class TestCaseExecuteTask : TestExecuteTask
    {
        public override TaskExecuteResult CollectTestParameters()
        {
            TaskExecuteResult result = TaskExecuteResult.SkippedTaskResult;
            Attribute testCase = GetMethodAttribute("NUnit.Framework.TestCaseAttribute");
            if (testCase == null)
                return result;
            
            foreach(Attribute testCaseItem in TestMethod.GetCustomAttributes(true))
            {
                if(testCaseItem == null)
                    continue;
                var testCaseType = testCaseItem.GetType();
                if(testCaseType == null || testCaseType.FullName != "NUnit.Framework.TestCaseAttribute")
                    continue;
                PropertyInfo prop = testCaseType.GetProperty("Arguments");
                if(prop == null)
                    continue;
                foreach(MethodInfo getter in prop.GetAccessors())
                {
                    object[] parameters = getter.Invoke(testCaseItem, Type.EmptyTypes) as object[];
                    result.AddParameters(parameters);
                }
            }
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;
This could be cleaned up some, and some of the magic strings extracted to constants,
but overall it is pretty simple. Basically what is going on here is that we are looking
for the TestCase attribute, and extracting the arguments for any attributes we find.&amp;nbsp;
It just so happens that the TestExecuteTask base class has a CollectTestParameters()
method we can override which allows for this sort of Row testing.&amp;nbsp; The parameters
we extract get stashed in the execution result, which causes the test runner to execute
the test once for each group of parameters (the result has a list of parameters, which
gets populated with an array of objects for each TestCase attribute), and will correctly
display which cases failed if there is a failure.
&lt;/p&gt;
&lt;p&gt;
There are a couple other small changes that need to happen to get this to work.&amp;nbsp;
There is an NUnitExtension.cs&amp;nbsp; class, which is the Plug-In class for the NUnit
support, and it handles wiring everything up for us.&amp;nbsp; First off we need to initialize
our new TestExecuteTask, and add it to the list of tasks that run for NUnit tests.&amp;nbsp;
We do that in the InitializePlugin method of the NUnitExtension class: &lt;pre class="brush: csharp"&gt;public override void InitializePlugin()
{
    base.InitializePlugin();
    nUnitProvider.AvailableTasks.Add(new NUnitIgnoreTask());
    nUnitProvider.AvailableTasks.Add(new NUnitSetupTearDownTask());
    nUnitProvider.AvailableTasks.Add(new NUnitExpectedExceptionTask());
    nUnitProvider.AvailableTasks.Add(new NUnitValuesTask());
    nUnitProvider.AvailableTasks.Add(new NUnitRowTestTask());
    nUnitProvider.AvailableTasks.Add(new NUnitTimeoutTask());
    nUnitProvider.AvailableTasks.Add(new NUnitExplicitTask());
    nUnitProvider.AvailableTasks.Add(new NUnitTestCaseTask());
}
&lt;/pre&gt;Ours
gets added to the end of the list, so it will be executed. The next step is to get
the plug-in to realize that a method with a TestCase attribute is an executable test
method. That trick happens in the handler for the CheckTestMethod event on the UnitTestProvider.
All we're going to do is add another condition to an if statement like so: &lt;pre class="brush: csharp"&gt;void nUnitProvider_CheckTestMethod(object sender, CheckTestMethodEventArgs ea)
{
    IMethodElement method = ea.Method;
    if(//method.Name != null &amp;amp;&amp;amp; method.Name.StartsWith("Test")
       ea.GetAttribute("NUnit.Framework", "Test", method) != null
    || ea.GetAttribute("NUnit.Framework.Extensions", "RowTest", method) != null
    || ea.GetAttribute("NUnit.Framework", "TestCase", method) != null)
    {
        ea.IsTestMethod = true;
        ea.Description = ea.GetAttributeText("NUnit.Framework", "Description", method);
        ea.Category = ea.GetAttributeText("NUnit.Framework", "Category", method);
    }
}
&lt;/pre&gt;
&lt;p&gt;
The only change to the original code was the additional GetAttribute call at the end
of the if statement (the comments were there when I got there, I swear).&amp;nbsp; Now
the only thing left to do is to compile it and drop it in the plug-ins directory.&amp;nbsp;
Now when you are looking at a test class, you should be able to run TestCase decorated
test methods without problem.&amp;nbsp; Well, almost.&amp;nbsp; There is one thing I was not
able to find a clean way to implement, and that is the Result property of the TestCase
attribute.&amp;nbsp; This allows you to streamline tests which are doing equals assertions
by having the test method return the actual result, and you specify the expected result
by using the result property.&amp;nbsp; Unfortunately I could not find a way to hook into
the actual execution of the test in such a way that I could have access to the specific
test properties being used, and the result of the test method execution.&amp;nbsp; But
considering the DevExpress folks will be fixing this issue, I’m sure when they release
it there will be support for this feature.&amp;nbsp; After all, this is simply a stop-gap
solution until the next CodeRush release is available, so I’m willing to live with
this slight inconvenience.
&lt;/p&gt;
&lt;p&gt;
Happy Testing!&amp;nbsp;&amp;nbsp; 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=49ad68e1-3159-4225-ab35-8c1a345429da" /&gt;</description>
      <comments>http://www.drrandom.org/CommentView,guid,49ad68e1-3159-4225-ab35-8c1a345429da.aspx</comments>
      <category>.Net</category>
      <category>C#</category>
      <category>CodeRush</category>
      <category>DxCore</category>
      <category>TDD</category>
      <category>tips</category>
    </item>
    <item>
      <trackback:ping>http://www.drrandom.org/Trackback.aspx?guid=ae83bded-50a9-4c93-85da-78a0da965f14</trackback:ping>
      <pingback:server>http://www.drrandom.org/pingback.aspx</pingback:server>
      <pingback:target>http://www.drrandom.org/PermaLink,guid,ae83bded-50a9-4c93-85da-78a0da965f14.aspx</pingback:target>
      <dc:creator>Casey Kramer</dc:creator>
      <wfw:comment>http://www.drrandom.org/CommentView,guid,ae83bded-50a9-4c93-85da-78a0da965f14.aspx</wfw:comment>
      <wfw:commentRss>http://www.drrandom.org/SyndicationService.asmx/GetEntryCommentsRss?guid=ae83bded-50a9-4c93-85da-78a0da965f14</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
As of right about now, you should be able to mosey on over to the <a href="http://code.google.com/p/dxcorecommunityplugins/" target="_blank">DxCore
Community Plug-ins page</a>, and grab a copy of <a href="http://code.google.com/p/dxcorecommunityplugins/wiki/CR_MoveFile" target="_blank">CR_MoveFile</a>. 
This is a plug-in I created primarily as a tool to aid in working in a TDD environment,
but which certainly has uses for non-TDD applications.  It does basically what <a href="http://www.drrandom.org/content/binary/WindowsLiveWriter/AnnouncingCR_MoveFileDxCorepluginformovi_8466/CR_MoveFile_ScreenShot_5.png"><img style="border-right-width: 0px; margin: 10px 0px 0px 20px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="CR_MoveFile_ScreenShot" border="0" alt="CR_MoveFile_ScreenShot" align="right" src="http://www.drrandom.org/content/binary/WindowsLiveWriter/AnnouncingCR_MoveFileDxCorepluginformovi_8466/CR_MoveFile_ScreenShot_thumb_1.png" width="660" height="439" /></a>the
name suggests, it allows you to move a file from one directory in your solution/project
structure to another, even one in a different project.  I implemented this as
a code provider (since it could change the functionality if you move the file from
one project to another), so it will appear in the Code menu when you have the cursor
somewhere within the beginning blocks of a file (“using” sections, namespace declaration,
or class/interface/struct declarations).  Once selected you are presented with
a popup window which has a tree that represents your current solution structure, with
your current directory highlighted.  You can use the arrow keys to navigate the
directories and choose a new home for your file.
</p>
        <p>
If you move files between projects, the plug-in will create project references for
you, so you don’t need to worry about that.  When the file is moved the file
contents remain unchanged, so all namespaces will be the same as they were originally. 
I did this mostly to keep the plug-in simple, but also because I could see situations
where this would be good, and situations where this would be bad, and it seemed like
this was a bad choice to make for people.  I’ve been using this plug-in on a
day-to-day basis for a while now, and things seem pretty clean, I did run into a small
issue, however, using it within a solution that was under source control.  At
this point you need to make sure the project files effected by the move are checked
out, otherwise the plug-in goes through the motions, but doesn’t actually do anything,
which is quite annoying.  There is also no checking going on to make sure the
language is the same between the source and target project, so if you work on a solution
that contains C# <strong>and</strong> VB.Net projects, you have to be careful not
to move files around to projects that can’t understand what they are (oh, and the
project icons used on the tree view are all the same, so there is no visual indication
of what project contains what type of files).
</p>
        <p>
That’s pretty much it.  Clean, simple, basic.  Used with other existing
CodeRush/Refactor tools like “Move Type To File” and “Move to Namespace”, this provides
for some pretty powerful code re-organization.  Just make sure you run all of
your tests :).
</p>
        <img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=ae83bded-50a9-4c93-85da-78a0da965f14" />
      </body>
      <title>Announcing CR_MoveFile: DxCore plug-in for moving files around in a solution</title>
      <guid isPermaLink="false">http://www.drrandom.org/PermaLink,guid,ae83bded-50a9-4c93-85da-78a0da965f14.aspx</guid>
      <link>http://www.drrandom.org/2009/12/07/AnnouncingCRMoveFileDxCorePluginForMovingFilesAroundInASolution.aspx</link>
      <pubDate>Mon, 07 Dec 2009 19:17:46 GMT</pubDate>
      <description>&lt;p&gt;
As of right about now, you should be able to mosey on over to the &lt;a href="http://code.google.com/p/dxcorecommunityplugins/" target="_blank"&gt;DxCore
Community Plug-ins page&lt;/a&gt;, and grab a copy of &lt;a href="http://code.google.com/p/dxcorecommunityplugins/wiki/CR_MoveFile" target="_blank"&gt;CR_MoveFile&lt;/a&gt;.&amp;nbsp;
This is a plug-in I created primarily as a tool to aid in working in a TDD environment,
but which certainly has uses for non-TDD applications.&amp;nbsp; It does basically what &lt;a href="http://www.drrandom.org/content/binary/WindowsLiveWriter/AnnouncingCR_MoveFileDxCorepluginformovi_8466/CR_MoveFile_ScreenShot_5.png"&gt;&lt;img style="border-right-width: 0px; margin: 10px 0px 0px 20px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="CR_MoveFile_ScreenShot" border="0" alt="CR_MoveFile_ScreenShot" align="right" src="http://www.drrandom.org/content/binary/WindowsLiveWriter/AnnouncingCR_MoveFileDxCorepluginformovi_8466/CR_MoveFile_ScreenShot_thumb_1.png" width="660" height="439"&gt;&lt;/a&gt;the
name suggests, it allows you to move a file from one directory in your solution/project
structure to another, even one in a different project.&amp;nbsp; I implemented this as
a code provider (since it could change the functionality if you move the file from
one project to another), so it will appear in the Code menu when you have the cursor
somewhere within the beginning blocks of a file (“using” sections, namespace declaration,
or class/interface/struct declarations).&amp;nbsp; Once selected you are presented with
a popup window which has a tree that represents your current solution structure, with
your current directory highlighted.&amp;nbsp; You can use the arrow keys to navigate the
directories and choose a new home for your file.
&lt;/p&gt;
&lt;p&gt;
If you move files between projects, the plug-in will create project references for
you, so you don’t need to worry about that.&amp;nbsp; When the file is moved the file
contents remain unchanged, so all namespaces will be the same as they were originally.&amp;nbsp;
I did this mostly to keep the plug-in simple, but also because I could see situations
where this would be good, and situations where this would be bad, and it seemed like
this was a bad choice to make for people.&amp;nbsp; I’ve been using this plug-in on a
day-to-day basis for a while now, and things seem pretty clean, I did run into a small
issue, however, using it within a solution that was under source control.&amp;nbsp; At
this point you need to make sure the project files effected by the move are checked
out, otherwise the plug-in goes through the motions, but doesn’t actually do anything,
which is quite annoying.&amp;nbsp; There is also no checking going on to make sure the
language is the same between the source and target project, so if you work on a solution
that contains C# &lt;strong&gt;and&lt;/strong&gt; VB.Net projects, you have to be careful not
to move files around to projects that can’t understand what they are (oh, and the
project icons used on the tree view are all the same, so there is no visual indication
of what project contains what type of files).
&lt;/p&gt;
&lt;p&gt;
That’s pretty much it.&amp;nbsp; Clean, simple, basic.&amp;nbsp; Used with other existing
CodeRush/Refactor tools like “Move Type To File” and “Move to Namespace”, this provides
for some pretty powerful code re-organization.&amp;nbsp; Just make sure you run all of
your tests :).
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=ae83bded-50a9-4c93-85da-78a0da965f14" /&gt;</description>
      <comments>http://www.drrandom.org/CommentView,guid,ae83bded-50a9-4c93-85da-78a0da965f14.aspx</comments>
      <category>.Net</category>
      <category>C#</category>
      <category>CodeRush</category>
      <category>DxCore</category>
      <category>TDD</category>
      <category>Tools</category>
    </item>
    <item>
      <trackback:ping>http://www.drrandom.org/Trackback.aspx?guid=7bb82e3b-a7d0-4fa5-9ac1-0f8e4261ed11</trackback:ping>
      <pingback:server>http://www.drrandom.org/pingback.aspx</pingback:server>
      <pingback:target>http://www.drrandom.org/PermaLink,guid,7bb82e3b-a7d0-4fa5-9ac1-0f8e4261ed11.aspx</pingback:target>
      <dc:creator>Casey Kramer</dc:creator>
      <wfw:comment>http://www.drrandom.org/CommentView,guid,7bb82e3b-a7d0-4fa5-9ac1-0f8e4261ed11.aspx</wfw:comment>
      <wfw:commentRss>http://www.drrandom.org/SyndicationService.asmx/GetEntryCommentsRss?guid=7bb82e3b-a7d0-4fa5-9ac1-0f8e4261ed11</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Anyone who has been around me for more than a few hours while coding, or who pays
any attention to me on <a href="http://www.twitter.com/drrandom">Twitter</a> will
know that I am a huge fan of <a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/">CodeRush
and Refactor Pro!</a> from <a href="http://www.devexpress.com">DevExpress</a>. 
I consider these sorts of tools essential to getting the most out of your development
environment, and I think CodeRush is one of the best tools available for a number
of reasons, not the least of which is it’s extensibility.  CodeRush is built
on top of <a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/DXCore/">DxCore</a>,
which is a freely available library for building Visual Studio plug-ins (incidentally,
DevExpress also have a free version of CodeRush called <a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/CodeRushX/">CodeRush
XPress</a>, which is built on the same platform).  DxCore provides any developer
who wants it access to the same tools that the folks at DevExpress have for building
plug-ins and extensions on top of VisualStudio, and several developers (including
yours truly) have <a href="http://code.google.com/p/dxcorecommunityplugins/">done
just that</a>.
</p>
        <p>
One of the more recent additions to the CodeRush arsenal are the CodeIssues. 
As of the v9 release, CodeRush included an extensive collection of these mini code
analyzers which will look at your code in real time and do everything from let you
know when you have undisposed resources, to suggesting alternate language features
you may not even be aware of.  A lot of these are also tied in to the refactoring
and code generation tools that already exist within CodeRush and Refactor Pro! so
that not only do you see that there is an issue or suggestion, but in a lot of cases
you can tell the tool to correct it for you.  Pretty impressive stuff.
</p>
        <p>
So what I would like to do is dig in to how the CodeIssue functionality works within
CodeRush by creating a custom CodeIssue Provider.  Because I’m a TDD guy, one
of the things I’ve been trying to do is build in some tooling around the TDD process
to make it that much easier to write code TDD.  So based on that I’m going to
show you how to implement a CodeRush CodeIssueProvider which will generate a warning
whenever you have created a Unit Test method with no assertions (which would indicate
that you are either dealing with an Integration Test, or your test is not correctly
factored).  <strong>Note:</strong> Since the CodeIssue UI elements are part of
the full CodeRush product, and not CodeRush XPress, this plug-in will note do anything
unless you are running the full version of CodeRush.
</p>
        <p>
Okay, so the first thing to do is to create a new Plug-In project.  This can
either be done from the Visual Studio File –&gt; New Project menu, or by selecting
the New Plug-in option from the DevExpress menu in visual studio (if you are using
CodeRush XPress and you don’t have the DevExpress menu, my man Rory Becker has a solution
for you).  Regardless of which way you go, you will get a “New DxCore Plug-in
Project” window, which will ask you what Language you want to write your plug-in in
(C# or Visual Basic .Net), and what kind of plug-in you want, along with the standard
stuff about what to name the solution and where to store the files.  For our
purposes we’re going to go with C# as the Language, a Standard Plug-in, and we’ll
call it CR_TestShouldAssert (the CR_ is a naming convention used by the CodeRush team
to indicate it’s a CodeRush plug-in, as opposed to a Refactoring or DxCore plug-in).
</p>
        <p>
          <a href="http://www.drrandom.org/content/binary/WindowsLiveWriter/GettingaCodeRushInsideaCodeRushCodeIssue_D816/image_2.png">
            <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.drrandom.org/content/binary/WindowsLiveWriter/GettingaCodeRushInsideaCodeRushCodeIssue_D816/image_thumb.png" width="745" height="393" />
          </a>
        </p>
        <p>
Net up is the “DxCore Plug-in Project Settings” dialog.  This allows you to give
your plug-in a title, and set some more advanced options which deal with how the plug-in
gets loaded by the DxCore framework.  We’ll just leave everything as-is and move
on to the good stuff.
</p>
        <p>
          <a href="http://www.drrandom.org/content/binary/WindowsLiveWriter/GettingaCodeRushInsideaCodeRushCodeIssue_D816/image_4.png">
            <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.drrandom.org/content/binary/WindowsLiveWriter/GettingaCodeRushInsideaCodeRushCodeIssue_D816/image_thumb_1.png" width="401" height="255" />
          </a>
        </p>
        <p>
Once your project loads you will be presented with a design surface, this is because
a large number of the components that are available via DXCore can actually be found
in the Visual Studio toolbox, and you can just drag them out onto your plug-in designer
to get started.  The CodeIssueProvider is an exception, though, so we will have
to crack open the designer file to add it to our plug-in.  So open up the PlugIn1.designer.cs
file, and add the following line of code under the “Windows Form Designer Generated
Code” section:
</p>
        <pre class="brush: csharp" name="code">CodeIssueProvider cipTestsShouldAssert;</pre>You'll
need to add a using statement for the DevExpress.CodeRush.Core namespace as well. 
Next we need to instantiate it, so we need to do this in the the InitializeComponents
method.  When you are finished your InitializeComponents method should look like
this:<pre class="brush: csharp" name="code">this.components = new System.ComponentModel.Container();
cipTestsShouldAssert = new CodeIssueProvider(this.components);
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();</pre><p>
Now if we switch back over to the designer, we will see our new provider on the design
surface.  At this point we can use the Properties window to configure the provider. 
The things we need to worry about filling out are the Description, DisplayName, and
ProviderName properties.  The Description is the text that will be displayed
in the Code Issue catalog, so it needs to clearly explain what the CodeIssueProvider
is intended to do.  Let’s go with something like: “A Unit Test should have at
least one explicit or implicit assertion.”  As for DisplayName, lets say something
like “Unit Test Method Should Assert”, and make the ProviderName the same.
</p><p>
Ok, so now it’s time to actually do the work of finding a TestMethod that violates
this condition.  So we need to switch over to the Events list for our provider,
and Double-Click in the CheckCodeIssues drop-down so it generates an event handler
for us.  You will now be taken to the code editor and presented with a empty
handler that looks something like:
</p><pre class="brush: csharp" name="code">private void cipTestsShouldAssert_CheckCodeIssues(object sender, CheckCodeIssuesEventArgs ea)
{

}</pre><p>
This looks pretty much like your normal event handler, we’ve got the sender object
(which would be our provider instance, and then we have a custom EventArgs object.
Looking at this event args object, you can see quite a few methods, and a couple of
properties.  The first few methods you see deal with actually adding your code
issue, if it exists, to the list of issues reported by the UI.  You’ve got one
method for each type of CodeIssue (AddDeadCode, AddError, AddHint, AddSmell,AddWarning),
and then one method (AddIssue), which allows you to specify the CodeIssue Type. 
Now this is where things start to get interesting because basically we’re at the point
where the good folks who wrote DxCore have said “All right, go off and find your problem
and report your finding back to me when your done”.  So from here we have to
figure out whether or not there are any test methods without asserts floating around
anywhere.  The good news is that there are a few tools in the CodeRush bag of
tricks that can help us.
</p><p>
Perhaps the best tool for figuring out this sort of thing is the “Expression Lab”
plug-in.  You can open this up by going to the DevExpress menu, opening the Tool
Windows-&gt;Diagnostics-&gt;Expressions Lab.  This shows you in real time what
the AST that CodeRush produces for your code looks like as you move about in a file. 
You can also see all of the properties associated with the various syntax elements,
and view how things are related.  This is a very handy tool to have.  Before
we dig too deep into the Expressions Lab, lets get a start on finding our CodeIssue. 
We know that we are going to be looking at methods here, since we are ultimately searching
for test methods, so the first thing to do is to limit the scope of our search to
just methods.  The CheckCodeIssues event is fired at a file level, so you are
basically handed an entire file to search by the DxCore framework.  We need to
filter that down a bit and only pay attention to the methods contained in the current
file.  To do that we’re going to use the ResolveScope() method of the CheckCodeIssuesEventArgs
object.  Calling the ResolveScope() method gives us a ScopreResolveResult object,
which doesn’t sound very interesting, but this object has a wonderful little method
on it called GetElementEnumerator().  This method will allow you to pass in a
filter expression, and return all of the elements that match that filter expression
as an enumerable collection. So to get to this, lets add the following to the body
of our event handler:
</p><pre class="brush: csharp" name="code">var resolveScope = ea.ResolveScope();
foreach(IMethodElement method in resolveScope.GetElementEnumerator(ea.Scope,new ElementTypeFilter(LanguageElementType.Method)))
{
}</pre><p>
This looks pretty straightforward, but there are a couple of things I want to point
out. First is the ea.Scope property that we are passing in to the GetElementEnumerable()
method. This is the AST object that represents the top of the parse-tree that we are
going to be searching for code issues in. Typically this is a file-level object, but
I don't know that you can count on that always being the case (changing the parse
settings could potentially effect how much of the code is considered invalid at a
time, and so you could get larger or smaller segments of code).  The other interesting
bit is the ElementTypeFilter().  This allows us to filter the list of AST elements
given to us in our enumerable based on their LangueElementType (LanguageElement is
the base class for syntax elements within the DxCore AST structure.  All nodes
have an ElementType property which exposes a LanguageElementType enum value). In our
case we’re only interested in methods, so we’re using LanguageElementType.Method. 
The result is a collection of all of the methods within our Scope.
</p><p>
Now that we have all of our methods, we need to figure out if they are Test methods. 
To do this we’ll have to look for the existence of an Attribute on the method. 
Taking a look at Expressions Lab, we can see that a Method object has an Attributes
collection associated with it. So we should be able to search the list of attributes
for one with a Name property of “Test”.  Using Linq, we can do this pretty easily
like this:
</p><pre class="brush: csharp" name="code">method.Attributes.OfType&lt;IAttributeElement&gt;().Count(a =&gt; a.Name == "Test")</pre>This
will give a a count of the "Test" attributes on our method. We can put this into an
if statement like so:<pre class="brush: csharp">if(method.Attributes.OfType&lt;IAttributeElement&gt;().Count(a =&gt; a.Name == "Test") &gt; 0)
{
}</pre>A
quick note; I'm using the OfType&lt;T&gt;() method to convert the collection returned
by the Attributes Property into an enumerable of IAttributeElements just as an easy
way of enabling Linq expressions against the collection. Since DxCore is written to
work with all versions of VisualStudio, there really isn't any official Linq support.
As a matter of fact, using the expression we did limits the plug-in to only those
people with .Net Framework 3.5 installed on their development machines. I think that
in this day and age, this is a fairly safe assumption, so I'm not that worried about
it. I would like to point out also, that having this expression in place does not
prevent the plug-in from working with Visual Studio 2005, as long as the 3.5 framework
is installed. 
<p></p><p>
Ok, so now we have a list of methods, and we’re filtering them based on whether or
not they are Test methods (defined by the existence of a Test attribute).  The
next thing to do is look for an Assert statement within the text of our method. 
This is another place where the Expressions Lab proves invaluable.  Looking at
Expressions Lab we discover that our Assert statement is in fact an ElementReferenceExpression
and is a child node of our Method object.  With this knowledge in hand we can
use the FindElementByName method on our Method object to look for an Assert reference:
</p><pre class="brush: csharp">var assert = method.FindChildByName("Assert") as IElementReferenceExpression</pre>Now
all we have to do is test whether or not our assert variable is null, and we know
whether or not this method violates our rule. Once we do that test we can add the
appropriate Code Issue Type to the CodeIssues list using our event args. The last
piece of the puzzle then will look something like this:<pre class="brush: csharp">if(assert == null)
{
    ea.AddIssue(CodeIssueType.CodeSmell,(SourceRange)method.NameRanges[0],"A Test Method should have at least one Assert");
}</pre><p>
With this in place we should now be able to run our project and try it out. Using
F5 to debug a DxCore plug-in will launch a new instance of Visual Studio. From there
if you create a new project, or open an existing project, and write a test method
which does not have an Assert, you should see a red squiggle underneath the name of
the method. Hovering over that with your mouse you'll see our Code Issue test presented.
Adding an Assert will make the Code Issue disappear.
</p><p><a href="http://www.drrandom.org/content/binary/WindowsLiveWriter/GettingaCodeRushInsideaCodeRushCodeIssue_D816/image_6.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.drrandom.org/content/binary/WindowsLiveWriter/GettingaCodeRushInsideaCodeRushCodeIssue_D816/image_thumb_2.png" width="498" height="136" /></a></p><p>
Well, things are looking good here, we’ve got code that is searching for an issue,
and displaying the appropriate warning if our condition is met.  There is one
other condition we should probably consider, however.  The one case I can think
of when our rule does not apply is when we are expecting the code under test to throw
an exception.  In that case there would be an ExpectedException attribute on
the test class.  To make our users happy we should probably implement this functionality.
</p><p>
The good news is we already know how to accomplish this, since we are using the same
technique to determine if the method we’re looking at is a test method.  All
we need to do is change the test condition in our Count() method so it looks for “ExpectedException”
instead of “Test”.  While we’re at it it seems like a reasonable thing to get
an instance of the attribute and then check it for null, similar to how we’re handling
the assert.  With all of this done the code should look like this:
</p><pre class="brush: csharp">var assert = method.FindChildByName("Assert") as IElementReferenceExpression;
var expectedException = method.Attributes.OfType&lt;IAttributeElement&gt;().FirstOrDefault(a =&gt; a.Name == "ExpectedException");
if (assert == null &amp;&amp; expectedException == null)
{
    ea.AddIssue(CodeIssueType.CodeSmell, (SourceRange)method.NameRanges[0], "A Test Method should have at least one implicit or explicit Assertion");
}</pre>So
now we should be able to run this, and see that the code issue disappears if we have
a test method with either an assert statement, or an expected exception attribute.
Pretty cool. You’ll notice that I also updated our issue message so it reflects the
fact that we are able to handle implicit assertions (in the form of our ExpectedException)
attribute.  For the sake of completeness, here is what our finished CheckCodeIssues
method looks like:<pre class="brush: csharp">private void cipTestShouldAssert_CheckCodeIssues(object sender, CheckCodeIssuesEventArgs ea)
{
    var resolveScope = ea.ResolveScope();
    foreach (IMethodElement method in resolveScope.GetElementEnumerator(ea.Scope, new ElementTypeFilter(LanguageElementType.Method)))
    {
        if (method.Attributes.OfType&lt;IAttributeElement&gt;().Count(a =&gt; a.Name == "Test") &gt; 0)
        {
            var assert = method.FindChildByName("Assert") as IElementReferenceExpression;
            var expectedException = method.Attributes.OfType&lt;IAttributeElement&gt;().FirstOrDefault(a =&gt; a.Name == "ExpectedException");
            if (assert == null &amp;&amp; expectedException == null)
            {
                ea.AddIssue(CodeIssueType.CodeSmell, (SourceRange)method.NameRanges[0], "A Test Method should have at least one implicit or explicit Assertion");
            }
        }
    }
}</pre><p>
And that's it. Granted there are some things here I would like to change before releasing
this into the wild. We are specifically looking for NUnit/MbUnit style test method
declarations for one, and we are also looking only for the short version of the attribute
names, but this should give you a good idea of how things work. 
</p><p>
If you are interested in seeing a more polished final version, you can either download
the <a href="http://www.drrandom.org/downloads/CR_TestShouldAssert.zip">finished source
for this post</a>, or have a look at my <a href="http://code.google.com/p/dxcorecommunityplugins/wiki/CR_CreateTestMethod">CR_CreateTestMethod</a> (admittedly
poorly named) plug-in on the <a href="http://code.google.com/p/dxcorecommunityplugins/">DxCore
Community Plug-In's site</a>.
</p><img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=7bb82e3b-a7d0-4fa5-9ac1-0f8e4261ed11" /></body>
      <title>Getting a CodeRush: Inside a CodeRush CodeIssue</title>
      <guid isPermaLink="false">http://www.drrandom.org/PermaLink,guid,7bb82e3b-a7d0-4fa5-9ac1-0f8e4261ed11.aspx</guid>
      <link>http://www.drrandom.org/2009/10/07/GettingACodeRushInsideACodeRushCodeIssue.aspx</link>
      <pubDate>Wed, 07 Oct 2009 17:22:35 GMT</pubDate>
      <description>&lt;p&gt;
Anyone who has been around me for more than a few hours while coding, or who pays
any attention to me on &lt;a href="http://www.twitter.com/drrandom"&gt;Twitter&lt;/a&gt; will
know that I am a huge fan of &lt;a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/"&gt;CodeRush
and Refactor Pro!&lt;/a&gt; from &lt;a href="http://www.devexpress.com"&gt;DevExpress&lt;/a&gt;.&amp;nbsp;
I consider these sorts of tools essential to getting the most out of your development
environment, and I think CodeRush is one of the best tools available for a number
of reasons, not the least of which is it’s extensibility.&amp;nbsp; CodeRush is built
on top of &lt;a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/DXCore/"&gt;DxCore&lt;/a&gt;,
which is a freely available library for building Visual Studio plug-ins (incidentally,
DevExpress also have a free version of CodeRush called &lt;a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/CodeRushX/"&gt;CodeRush
XPress&lt;/a&gt;, which is built on the same platform).&amp;nbsp; DxCore provides any developer
who wants it access to the same tools that the folks at DevExpress have for building
plug-ins and extensions on top of VisualStudio, and several developers (including
yours truly) have &lt;a href="http://code.google.com/p/dxcorecommunityplugins/"&gt;done
just that&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
One of the more recent additions to the CodeRush arsenal are the CodeIssues.&amp;nbsp;
As of the v9 release, CodeRush included an extensive collection of these mini code
analyzers which will look at your code in real time and do everything from let you
know when you have undisposed resources, to suggesting alternate language features
you may not even be aware of.&amp;nbsp; A lot of these are also tied in to the refactoring
and code generation tools that already exist within CodeRush and Refactor Pro! so
that not only do you see that there is an issue or suggestion, but in a lot of cases
you can tell the tool to correct it for you.&amp;nbsp; Pretty impressive stuff.
&lt;/p&gt;
&lt;p&gt;
So what I would like to do is dig in to how the CodeIssue functionality works within
CodeRush by creating a custom CodeIssue Provider.&amp;nbsp; Because I’m a TDD guy, one
of the things I’ve been trying to do is build in some tooling around the TDD process
to make it that much easier to write code TDD.&amp;nbsp; So based on that I’m going to
show you how to implement a CodeRush CodeIssueProvider which will generate a warning
whenever you have created a Unit Test method with no assertions (which would indicate
that you are either dealing with an Integration Test, or your test is not correctly
factored).&amp;nbsp; &lt;strong&gt;Note:&lt;/strong&gt; Since the CodeIssue UI elements are part of
the full CodeRush product, and not CodeRush XPress, this plug-in will note do anything
unless you are running the full version of CodeRush.
&lt;/p&gt;
&lt;p&gt;
Okay, so the first thing to do is to create a new Plug-In project.&amp;nbsp; This can
either be done from the Visual Studio File –&amp;gt; New Project menu, or by selecting
the New Plug-in option from the DevExpress menu in visual studio (if you are using
CodeRush XPress and you don’t have the DevExpress menu, my man Rory Becker has a solution
for you).&amp;nbsp; Regardless of which way you go, you will get a “New DxCore Plug-in
Project” window, which will ask you what Language you want to write your plug-in in
(C# or Visual Basic .Net), and what kind of plug-in you want, along with the standard
stuff about what to name the solution and where to store the files.&amp;nbsp; For our
purposes we’re going to go with C# as the Language, a Standard Plug-in, and we’ll
call it CR_TestShouldAssert (the CR_ is a naming convention used by the CodeRush team
to indicate it’s a CodeRush plug-in, as opposed to a Refactoring or DxCore plug-in).
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.drrandom.org/content/binary/WindowsLiveWriter/GettingaCodeRushInsideaCodeRushCodeIssue_D816/image_2.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.drrandom.org/content/binary/WindowsLiveWriter/GettingaCodeRushInsideaCodeRushCodeIssue_D816/image_thumb.png" width="745" height="393"&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
Net up is the “DxCore Plug-in Project Settings” dialog.&amp;nbsp; This allows you to give
your plug-in a title, and set some more advanced options which deal with how the plug-in
gets loaded by the DxCore framework.&amp;nbsp; We’ll just leave everything as-is and move
on to the good stuff.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.drrandom.org/content/binary/WindowsLiveWriter/GettingaCodeRushInsideaCodeRushCodeIssue_D816/image_4.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.drrandom.org/content/binary/WindowsLiveWriter/GettingaCodeRushInsideaCodeRushCodeIssue_D816/image_thumb_1.png" width="401" height="255"&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
Once your project loads you will be presented with a design surface, this is because
a large number of the components that are available via DXCore can actually be found
in the Visual Studio toolbox, and you can just drag them out onto your plug-in designer
to get started.&amp;nbsp; The CodeIssueProvider is an exception, though, so we will have
to crack open the designer file to add it to our plug-in.&amp;nbsp; So open up the PlugIn1.designer.cs
file, and add the following line of code under the “Windows Form Designer Generated
Code” section:&lt;pre class="brush: csharp" name="code"&gt;CodeIssueProvider cipTestsShouldAssert;&lt;/pre&gt;You'll
need to add a using statement for the DevExpress.CodeRush.Core namespace as well.&amp;nbsp;
Next we need to instantiate it, so we need to do this in the the InitializeComponents
method.&amp;nbsp; When you are finished your InitializeComponents method should look like
this:&lt;pre class="brush: csharp" name="code"&gt;this.components = new System.ComponentModel.Container();
cipTestsShouldAssert = new CodeIssueProvider(this.components);
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();&lt;/pre&gt;
&lt;p&gt;
Now if we switch back over to the designer, we will see our new provider on the design
surface.&amp;nbsp; At this point we can use the Properties window to configure the provider.&amp;nbsp;
The things we need to worry about filling out are the Description, DisplayName, and
ProviderName properties.&amp;nbsp; The Description is the text that will be displayed
in the Code Issue catalog, so it needs to clearly explain what the CodeIssueProvider
is intended to do.&amp;nbsp; Let’s go with something like: “A Unit Test should have at
least one explicit or implicit assertion.”&amp;nbsp; As for DisplayName, lets say something
like “Unit Test Method Should Assert”, and make the ProviderName the same.
&lt;/p&gt;
&lt;p&gt;
Ok, so now it’s time to actually do the work of finding a TestMethod that violates
this condition.&amp;nbsp; So we need to switch over to the Events list for our provider,
and Double-Click in the CheckCodeIssues drop-down so it generates an event handler
for us.&amp;nbsp; You will now be taken to the code editor and presented with a empty
handler that looks something like:&lt;pre class="brush: csharp" name="code"&gt;private void cipTestsShouldAssert_CheckCodeIssues(object sender, CheckCodeIssuesEventArgs ea)
{

}&lt;/pre&gt;
&lt;p&gt;
This looks pretty much like your normal event handler, we’ve got the sender object
(which would be our provider instance, and then we have a custom EventArgs object.
Looking at this event args object, you can see quite a few methods, and a couple of
properties.&amp;nbsp; The first few methods you see deal with actually adding your code
issue, if it exists, to the list of issues reported by the UI.&amp;nbsp; You’ve got one
method for each type of CodeIssue (AddDeadCode, AddError, AddHint, AddSmell,AddWarning),
and then one method (AddIssue), which allows you to specify the CodeIssue Type.&amp;nbsp;
Now this is where things start to get interesting because basically we’re at the point
where the good folks who wrote DxCore have said “All right, go off and find your problem
and report your finding back to me when your done”.&amp;nbsp; So from here we have to
figure out whether or not there are any test methods without asserts floating around
anywhere.&amp;nbsp; The good news is that there are a few tools in the CodeRush bag of
tricks that can help us.
&lt;/p&gt;
&lt;p&gt;
Perhaps the best tool for figuring out this sort of thing is the “Expression Lab”
plug-in.&amp;nbsp; You can open this up by going to the DevExpress menu, opening the Tool
Windows-&amp;gt;Diagnostics-&amp;gt;Expressions Lab.&amp;nbsp; This shows you in real time what
the AST that CodeRush produces for your code looks like as you move about in a file.&amp;nbsp;
You can also see all of the properties associated with the various syntax elements,
and view how things are related.&amp;nbsp; This is a very handy tool to have.&amp;nbsp; Before
we dig too deep into the Expressions Lab, lets get a start on finding our CodeIssue.&amp;nbsp;
We know that we are going to be looking at methods here, since we are ultimately searching
for test methods, so the first thing to do is to limit the scope of our search to
just methods.&amp;nbsp; The CheckCodeIssues event is fired at a file level, so you are
basically handed an entire file to search by the DxCore framework.&amp;nbsp; We need to
filter that down a bit and only pay attention to the methods contained in the current
file.&amp;nbsp; To do that we’re going to use the ResolveScope() method of the CheckCodeIssuesEventArgs
object.&amp;nbsp; Calling the ResolveScope() method gives us a ScopreResolveResult object,
which doesn’t sound very interesting, but this object has a wonderful little method
on it called GetElementEnumerator().&amp;nbsp; This method will allow you to pass in a
filter expression, and return all of the elements that match that filter expression
as an enumerable collection. So to get to this, lets add the following to the body
of our event handler:&lt;pre class="brush: csharp" name="code"&gt;var resolveScope = ea.ResolveScope();
foreach(IMethodElement method in resolveScope.GetElementEnumerator(ea.Scope,new ElementTypeFilter(LanguageElementType.Method)))
{
}&lt;/pre&gt;
&lt;p&gt;
This looks pretty straightforward, but there are a couple of things I want to point
out. First is the ea.Scope property that we are passing in to the GetElementEnumerable()
method. This is the AST object that represents the top of the parse-tree that we are
going to be searching for code issues in. Typically this is a file-level object, but
I don't know that you can count on that always being the case (changing the parse
settings could potentially effect how much of the code is considered invalid at a
time, and so you could get larger or smaller segments of code).&amp;nbsp; The other interesting
bit is the ElementTypeFilter().&amp;nbsp; This allows us to filter the list of AST elements
given to us in our enumerable based on their LangueElementType (LanguageElement is
the base class for syntax elements within the DxCore AST structure.&amp;nbsp; All nodes
have an ElementType property which exposes a LanguageElementType enum value). In our
case we’re only interested in methods, so we’re using LanguageElementType.Method.&amp;nbsp;
The result is a collection of all of the methods within our Scope.
&lt;/p&gt;
&lt;p&gt;
Now that we have all of our methods, we need to figure out if they are Test methods.&amp;nbsp;
To do this we’ll have to look for the existence of an Attribute on the method.&amp;nbsp;
Taking a look at Expressions Lab, we can see that a Method object has an Attributes
collection associated with it. So we should be able to search the list of attributes
for one with a Name property of “Test”.&amp;nbsp; Using Linq, we can do this pretty easily
like this:&lt;pre class="brush: csharp" name="code"&gt;method.Attributes.OfType&amp;lt;IAttributeElement&amp;gt;().Count(a =&amp;gt; a.Name == "Test")&lt;/pre&gt;This
will give a a count of the "Test" attributes on our method. We can put this into an
if statement like so:&lt;pre class="brush: csharp"&gt;if(method.Attributes.OfType&amp;lt;IAttributeElement&amp;gt;().Count(a =&amp;gt; a.Name == "Test") &amp;gt; 0)
{
}&lt;/pre&gt;A
quick note; I'm using the OfType&amp;lt;T&amp;gt;() method to convert the collection returned
by the Attributes Property into an enumerable of IAttributeElements just as an easy
way of enabling Linq expressions against the collection. Since DxCore is written to
work with all versions of VisualStudio, there really isn't any official Linq support.
As a matter of fact, using the expression we did limits the plug-in to only those
people with .Net Framework 3.5 installed on their development machines. I think that
in this day and age, this is a fairly safe assumption, so I'm not that worried about
it. I would like to point out also, that having this expression in place does not
prevent the plug-in from working with Visual Studio 2005, as long as the 3.5 framework
is installed. 
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
Ok, so now we have a list of methods, and we’re filtering them based on whether or
not they are Test methods (defined by the existence of a Test attribute).&amp;nbsp; The
next thing to do is look for an Assert statement within the text of our method.&amp;nbsp;
This is another place where the Expressions Lab proves invaluable.&amp;nbsp; Looking at
Expressions Lab we discover that our Assert statement is in fact an ElementReferenceExpression
and is a child node of our Method object.&amp;nbsp; With this knowledge in hand we can
use the FindElementByName method on our Method object to look for an Assert reference:&lt;pre class="brush: csharp"&gt;var assert = method.FindChildByName("Assert") as IElementReferenceExpression&lt;/pre&gt;Now
all we have to do is test whether or not our assert variable is null, and we know
whether or not this method violates our rule. Once we do that test we can add the
appropriate Code Issue Type to the CodeIssues list using our event args. The last
piece of the puzzle then will look something like this:&lt;pre class="brush: csharp"&gt;if(assert == null)
{
    ea.AddIssue(CodeIssueType.CodeSmell,(SourceRange)method.NameRanges[0],"A Test Method should have at least one Assert");
}&lt;/pre&gt;
&lt;p&gt;
With this in place we should now be able to run our project and try it out. Using
F5 to debug a DxCore plug-in will launch a new instance of Visual Studio. From there
if you create a new project, or open an existing project, and write a test method
which does not have an Assert, you should see a red squiggle underneath the name of
the method. Hovering over that with your mouse you'll see our Code Issue test presented.
Adding an Assert will make the Code Issue disappear.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.drrandom.org/content/binary/WindowsLiveWriter/GettingaCodeRushInsideaCodeRushCodeIssue_D816/image_6.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.drrandom.org/content/binary/WindowsLiveWriter/GettingaCodeRushInsideaCodeRushCodeIssue_D816/image_thumb_2.png" width="498" height="136"&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
Well, things are looking good here, we’ve got code that is searching for an issue,
and displaying the appropriate warning if our condition is met.&amp;nbsp; There is one
other condition we should probably consider, however.&amp;nbsp; The one case I can think
of when our rule does not apply is when we are expecting the code under test to throw
an exception.&amp;nbsp; In that case there would be an ExpectedException attribute on
the test class.&amp;nbsp; To make our users happy we should probably implement this functionality.
&lt;/p&gt;
&lt;p&gt;
The good news is we already know how to accomplish this, since we are using the same
technique to determine if the method we’re looking at is a test method.&amp;nbsp; All
we need to do is change the test condition in our Count() method so it looks for “ExpectedException”
instead of “Test”.&amp;nbsp; While we’re at it it seems like a reasonable thing to get
an instance of the attribute and then check it for null, similar to how we’re handling
the assert.&amp;nbsp; With all of this done the code should look like this:&lt;pre class="brush: csharp"&gt;var assert = method.FindChildByName("Assert") as IElementReferenceExpression;
var expectedException = method.Attributes.OfType&amp;lt;IAttributeElement&amp;gt;().FirstOrDefault(a =&amp;gt; a.Name == "ExpectedException");
if (assert == null &amp;amp;&amp;amp; expectedException == null)
{
    ea.AddIssue(CodeIssueType.CodeSmell, (SourceRange)method.NameRanges[0], "A Test Method should have at least one implicit or explicit Assertion");
}&lt;/pre&gt;So
now we should be able to run this, and see that the code issue disappears if we have
a test method with either an assert statement, or an expected exception attribute.
Pretty cool. You’ll notice that I also updated our issue message so it reflects the
fact that we are able to handle implicit assertions (in the form of our ExpectedException)
attribute.&amp;nbsp; For the sake of completeness, here is what our finished CheckCodeIssues
method looks like:&lt;pre class="brush: csharp"&gt;private void cipTestShouldAssert_CheckCodeIssues(object sender, CheckCodeIssuesEventArgs ea)
{
    var resolveScope = ea.ResolveScope();
    foreach (IMethodElement method in resolveScope.GetElementEnumerator(ea.Scope, new ElementTypeFilter(LanguageElementType.Method)))
    {
        if (method.Attributes.OfType&amp;lt;IAttributeElement&amp;gt;().Count(a =&amp;gt; a.Name == "Test") &amp;gt; 0)
        {
            var assert = method.FindChildByName("Assert") as IElementReferenceExpression;
            var expectedException = method.Attributes.OfType&amp;lt;IAttributeElement&amp;gt;().FirstOrDefault(a =&amp;gt; a.Name == "ExpectedException");
            if (assert == null &amp;amp;&amp;amp; expectedException == null)
            {
                ea.AddIssue(CodeIssueType.CodeSmell, (SourceRange)method.NameRanges[0], "A Test Method should have at least one implicit or explicit Assertion");
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;
And that's it. Granted there are some things here I would like to change before releasing
this into the wild. We are specifically looking for NUnit/MbUnit style test method
declarations for one, and we are also looking only for the short version of the attribute
names, but this should give you a good idea of how things work. 
&lt;/p&gt;
&lt;p&gt;
If you are interested in seeing a more polished final version, you can either download
the &lt;a href="http://www.drrandom.org/downloads/CR_TestShouldAssert.zip"&gt;finished source
for this post&lt;/a&gt;, or have a look at my &lt;a href="http://code.google.com/p/dxcorecommunityplugins/wiki/CR_CreateTestMethod"&gt;CR_CreateTestMethod&lt;/a&gt; (admittedly
poorly named) plug-in on the &lt;a href="http://code.google.com/p/dxcorecommunityplugins/"&gt;DxCore
Community Plug-In's site&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=7bb82e3b-a7d0-4fa5-9ac1-0f8e4261ed11" /&gt;</description>
      <comments>http://www.drrandom.org/CommentView,guid,7bb82e3b-a7d0-4fa5-9ac1-0f8e4261ed11.aspx</comments>
      <category>.Net</category>
      <category>C#</category>
      <category>CodeRush</category>
      <category>DxCore</category>
      <category>Tools</category>
    </item>
  </channel>
</rss>