About Me

Training

Nothin But .Net Developer Bootcamp

Navigation

Search

Categories

On this page

Another Rhino Mocks extension method to support your AAA style
VS + ViEmu + (ReSharper modded with AutoHotkey)
BDD, AAA Style Testing and Rhino Mocks
Staying Humble
Small Update to BDD Macro
Solution Reorganizing (Again!!)
Got Icons?
Got A Spotter?
Score 1 For Eliminating your hands flight path
BDD Test Naming Macro - Speed Update
IMapper
BDD Specification Base Class
Nothin But .Net Store (Google Code) Breaking Change
MappingEnumerable
Getting started with BDD style Context/Specification base naming
Setting The Record Straight - My Thoughts On The MVP Variants (for web applications)
code.google.com/p/jpboodhoo!!!
Stop Reading - Start Doing
Huge Code Drop Coming!!!!!!!
The Static Gateway Pattern
Start Flying With ReSharper (and windows in general) - Use the Alt-Key
Drop the temporary lists and leverage yield
Screen Bound DTO Update (Getting the terminology right)
Screen Bound DTO's (Presentation Model)
Macro to aid BDD test naming style
Nothin But .Net - New York , NY ( October 22nd - 26th, 2007 )
Essential (almost) Language Agnostic Programming Books
The Bible's Take On Separation Of Responsibility
Read any good books lately?
Multithreading Question - One Solution
Learning Some New Stuff - Adapting And Filtering
The Open Closed Principle. - How Far Do You Take It
One Class To Rule Them All
Best Of Compendium!!

Archive

Blogroll

 Agile Developer Venkat's Blog
 Ayende @ Blog
 B#
 Barry Gervin's Software Architecture Perspectives
 Boy Meets World
 Brad Abrams
 Canadian Developers
 Christopher Steen
 Claritude Software News
 Clemens Vasters: Enterprise Development and Alien Abductions
 Coding Horror
 Coding in an Igloo
 Dare Obasanjo aka Carnage4Life
 Darrell Norton's Blog [MVP]
 David Hayden [MVP C#]
 Don Box's Spoutlet
 Eric Gunnerson's C# Compendium
 EZWeb guy: Jeffrey Palermo [C# MVP]
 Fear and Loathing
 Generalities & Details: Adventures in the High-tech Underbelly
 Greg Young [MVP]
 Greg's Cool [Insert Clever Name] of the Day
 IanG on Tap
 Ingo Rammer's Weblog
 ISerializable - Roy Osherove's Blog
 James Kovacs' Weblog
 Jason Haley
 Jean-Luc David
 Jeremy D. Miller -- The Shade Tree Developer
 JetBrains .NET Tools Blog
 Jimmy Nilsson's weblog
 John Bristowe's Weblog
 John Papa [MVP C#]
 Jon Skeet's Coding Blog
 JonGalloway.ToString()
 Jump the Fence or Walk Around
 Lambda the Ultimate - Programming Languages Weblog
 Larkware News
 Lutz Roeder
 Marquee de Sells: Chris's insight outlet
 Martin Fowler's Bliki
 Mike Nichols - SonOfNun Technology
 MSDN Magazine - .NET Matters
 MSDN Magazine - All Articles
 OdeToCode Blogs
 Onion Blog
 Planet TW
 Raymond Lewallen [MVP]
 Rockford Lhotka
 RodMan's Corner
 Roger Johansson's blog
 Sahil Malik - blah.winsmarts.com
 Sam Gentile's Blog
 Scott Bellware [MVP]
 Scott Hanselman's Computer Zen
 ScottGu's Blog
 secretGeek
 Service Station, by Aaron Skonnard
 Signum sine tinnitu--by Guy Kawasaki
 Stephen Toub
 Steve Eichert's Blog
 Steven Rockarts
 The Blog Ride
 The Coding Hillbilly
 The Daily WTF
 TheServerSide.net: News
 Tim Gifford
 Vance Morrison's Weblog
 you've been HAACKED

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 407
This Year: 132
This Month: 3
This Week: 0
Comments: 1082

 Saturday, August 30, 2008
Saturday, August 30, 2008 4:49:16 PM (Mountain Standard Time, UTC-07:00) ( Programming )
If you want to carry on setting expectations on void methods on your mocks, just use the following method

public static IMethodOptions when_told_to(this T mock, Action action)
{
     return mock.Expect(action);
}

Here is an example of the usage:


db_connection.when_told_to(x => x.Open()) .Throw(new Exception());

Just another small play on words, but I like the readability of it. Develop With Passion!!
Comments [1] | | # 
 Thursday, July 31, 2008
Thursday, July 31, 2008 2:00:43 PM (Mountain Standard Time, UTC-07:00) ( Programming )

Now that I have been using Vim for a couple of months I feel very comfortable with it. Thanks to someone in my last class who has been a Vim user for years, I have started to use Vim for more than just editing (more on that in a later post). Vim has permeated a lot of the applications that I use:

  • Firefox
  • Visual Studio
  • Word
  • SQL Server Management Studio

 

Anyone who knows me well is aware of the fact that I am a keyboard junkie who is obsessed with keeping my hands as close to home row as possible! This is why for the longest time I have not used the ALT-Insert Resharper shortcut, but rather ALT-R-C-G-I, which is the traversal path to get to the ReSharper generate dialog.

Some of the features that I love about ReSharper also require the use of arrow keys, features such as:

  • Go to next member/tag
  • Go to previous member/tag
  • Move code up
  • Move code down
  • Go to next usage
  • Go to previous usage

I use ViEmu in studio, but also use ReSharper for the awesome features it provides. As cool as the above ReSharper features are, I have never liked having to reach for the arrow keys (or memorize the menu traversal path) when editing with ReSharper. A couple of days ago I decided to use AutoHotkey to allow me to tweak the keyboard so that I could perform all of the above operations using the exact keystrokes as ReSharper except replacing the use of the arrow keys with the appropriate Vim alternative (H,J,K,L). So now I can do the above as follows:

  • Go to next member/tag
    • Original - Alt + Down Arrow
    • Now - Alt + J
  • Go to previous member/tag
    • Original - Alt + Up Arrow
    • Now - Alt + K
  • Move code up
    • Original - Ctrl + Shift + Alt + Up Arrow
    • Now - Ctrl + Shift + Alt + K
  • Move code down
    • Original - Ctrl + Shift + Alt + Down Arrow
    • Now - Ctrl + Shift + Alt + J
  • Go to next usage
    • Original - Ctrl + Alt + Down Arrow
    • Now - Shift + Alt + J
  • Go to previous usage
    • Original - Ctrl + Alt + Up Arrow
    • Now - Shift + Alt + J
  • Generate Code
    • Original - Alt - Insert
    • Now - Alt + I

 

Only the go to next usage functions got a key replacement (Shift instead of Ctrl). Of course, none of the scripts affect the original ReSharper shortcuts, so when I am pairing with someone proficient with ReSharper and not Vim, they do not have an issue as they don't need to use the alternatives (and I can hit the shortcut to temporarily disable ViEmu also). They can carry on using the original ReSharper shortcuts. Notice that I also did the Generate Code so that now I can just hit ALT + I to do the same thing as ALT - Insert (no flight path for the hands at all!!). The nice thing is that now I can pull off all of the above functionality without having to leave home row and I get the benefit of consistent Vim style navigation.

 

Here are the scripts (simplified for brevity):

;=============================
;Process Go to next member/tag
;=============================
$!J::
    Send, !{Down}
return

;=================================
;Process Go to previous member/tag
;=================================
$!K::
    Send, !{Up}
return

;==========================
;Process Move Code Up
;==========================
$^+!K::
    Send, ^+!{Up}
return

;==========================
;Process Move Code Down
;==========================
$^+!J::
    Send, ^+!{Down}
return

;==========================
;Process Go to next usage
;==========================
$+!J::
    Send, ^!{Down}
return

;==========================
;Process Go to previous usage
;==========================
$+!k::
    Send, ^!{Up}
return

;==========================
;Process Generate Code
;==========================
$!I::
    Send, !{Insert}
return

 

Develop With Passion!!

Comments [2] | | # 
 Friday, June 13, 2008
Friday, June 13, 2008 5:47:58 PM (Mountain Standard Time, UTC-07:00) ( C# | Programming )

Having downloaded and started to use Rhino Mocks 3.5 beta pretty much as soon as Oren released. I am very happy with the AAA style (Arrange, Act, Assert) and the readability and brevity it has brought to my tests. The current project I am on has a huge set of tests. Here is an example of using Rhino Mocks, in conjunction with some BDD style naming:

[Concern(typeof (UnitOfWorkFactory))] public class When_a_new_unit_of_work_is_requested_to_be_created : behaves_like_unit_of_work_with_scope_storage_in_play { protected override void because() { sut.Create(); } [Observation] public void Should_access_scoped_storage_to_determine_if_a_unit_of_work_is_already_active() { scoped_storage.was_told_to(item => item.DoesNotContain<IUnitOfWork>()); } } [Concern(typeof (UnitOfWorkFactory))] public class When_creating_a_unit_of_work_and_the_scoped_storage_does_not_contain_an_active_unit_of_work : behaves_like_unit_of_work_with_scope_storage_in_play { private ISession session; protected override void establish_context() { base.establish_context(); session = Dependency<ISession>(); scoped_storage.setup_result(item => item.DoesNotContain<IUnitOfWork>()).Return(true); nhibernate_session_factory.setup_result(item => item.OpenSession()).Return(session); } protected override void because() { sut.Create(); } [Observation] public void Should_store_the_newly_created_unit_of_work_in_scoped_storage() { scoped_storage.was_told_to(item => item.Store(Arg<IUnitOfWork>.Matches(uow => uow != null))); } } [Concern(typeof (UnitOfWorkFactory))] public class When_a_new_unit_of_work_is_requested_and_one_already_exists_in_scoped_storage : behaves_like_unit_of_work_with_scope_storage_in_play { private ISession session; private IUnitOfWork new_unit_of_work; private IUnitOfWork active_unit_of_work; protected override void establish_context() { base.establish_context(); session = Dependency<ISession>(); active_unit_of_work = Dependency<IUnitOfWork>(); nhibernate_session_factory.setup_result(item => item.OpenSession()).Return(session); scoped_storage.setup_result(item => item.Contains<IUnitOfWork>()).Return(true); scoped_storage.setup_result(item => item.Retrieve<IUnitOfWork>()).Return(active_unit_of_work); } protected override void because() { new_unit_of_work = sut.Create(); } [Observation] public void Should_return_a_non_disposing_unit_of_work_proxy() { new_unit_of_work.should_be_an_instance_of<NonDisposableUnitOfWork>(); } }
 

I am no longer using the automocking container so you are probably wondering what the Dependency method call is all about. It is simply a method defined on a base ContextSpecification class whose definition is as follows:

 

[Context] public abstract class ContextSpecification { [SetUp] public void setup() { unit_test_container.Initialize(); establish_context(); because(); } [TearDown] public void teardown() { after_each_specification(); unit_test_container.tear_down_and_unregister_from_dependency_registry(); } protected abstract void because(); protected abstract void establish_context(); protected virtual void after_each_specification() { } protected InterfaceType Dependency<InterfaceType>() { return MockRepository.GenerateMock<InterfaceType>(); } protected InterfaceType Stub<InterfaceType>() { return MockRepository.GenerateStub<InterfaceType>(); } }

And I have some extension methods that wrap the RhinoMocks "assertions" with more language oriented assertions: Instead of AssertWasCalled you get was_told_to, and so on.

 

Develop With Passion!!

Comments [5] | | # 
 Tuesday, June 03, 2008
Tuesday, June 03, 2008 2:33:53 AM (Mountain Standard Time, UTC-07:00) ( Insipration | Programming )

This post is in direct reference to the brilliant paper titled "The Humble Programmer" written by the software genius Edsger Dijkstra.

If you take the time to read this paper, keep in mind that it was originally published in 1972!! Here are 2 (of the many) that resound very strongly with me:

"But one should not first make the program and then prove its correctness, because then the requirement of providing the proof would only increase the poor programmer's burden. On the contrary: the programmer should let correctness proof and program grow hand in hand. Argument three is essentially based on the following observation. If one first asks oneself what the structure of a convincing proof would be and, having found this, then constructs a program satisfying this proof's requirements, then these correctness concerns turn out to be a very effective heuristic guidance. By definition this approach is only applicable when we restrict ourselves to intellectually manageable programs, but it provides us with effective means for finding a satisfactory one among these."

If that section in bold does not scream TDD to you, then I don't know what will!!

Another good section talking about languages and how we can abuse them is here:

"The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague. In the case of a well-known conversational programming language I have been told from various sides that as soon as a programming community is equipped with a terminal for it, a specific phenomenon occurs that even has a well-established name: it is called "the one-liners". It takes one of two different forms: one programmer places a one-line program on the desk of another and either he proudly tells what it does and adds the question "Can you code this in less symbols?" —as if this were of any conceptual relevance!— or he just asks "Guess what it does!". From this observation we must conclude that this language as a tool is an open invitation for clever tricks; and while exactly this may be the explanation for some of its appeal, viz. to those who like to show how clever they are, I am sorry, but I must regard this as one of the most damning things that can be said about a programming language"

And finally he shares a piece of advice that is awesome:

"We shall do a much better programming job, provided that we approach the task with a full appreciation of its tremendous difficulty, provided that we stick to modest and elegant programming languages, provided that we respect the intrinsic limitations of the human mind and approach the task as Very Humble Programmers"

Brilliant advice from an equally brilliant man!!

Develop With Passion

Comments [4] | | # 
 Monday, May 19, 2008
Monday, May 19, 2008 2:13:36 PM (Mountain Standard Time, UTC-07:00) ( Programming )

I noticed a small error in the BDD macro that I have just fixed. The text of the macro is below:

Imports System

Imports System.Windows.Forms
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics

Public Module CodeEditor

    Public Sub ReplaceSpacesInTestNameWithUnderscores()
        If DTE.ActiveDocument Is Nothing Then Return
        Dim wrCS As Boolean = DTE.Properties("TextEditor", "CSharp").Item("WordWrap").Value

        Try
            DTE.Properties("TextEditor", "CSharp").Item("WordWrap").Value = False
            Dim selection As TextSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection)
            Dim index As Integer

            selection.SelectLine()
            If selection.Text = "" Then Return

            Dim methodIndex As Integer = selection.Text.IndexOf("public void ")
            Dim classIndex As Integer = selection.Text.IndexOf("public class ")

            If (methodIndex < 0 AndAlso classIndex < 0) Then Return

            index = CType(IIf(methodIndex >= 0, methodIndex, classIndex), Integer)

            Dim prefix As String = CType(IIf(methodIndex >= 0, "public void ", "public class "), String)
            Dim whiteSpace As String = selection.Text.Substring(0, index)
            prefix = whiteSpace + prefix
            Dim description As String = selection.Text.Replace(prefix, String.Empty).Trim
            Dim text As String = prefix + description.Replace(" ", "_").Replace("'", "_") + vbCrLf
            selection.Delete()
            selection.Insert(text)
            selection.LineUp()
            selection.LineUp()
            selection.SelectLine()
            If selection.Text.Trim = "{" Or selection.Text.Trim = "}" Or selection.Text.Trim = "" Then
                If selection.Text.Trim = "{" Or selection.Text.Trim = "}" Then
                    selection.Insert(selection.Text.Replace(vbCrLf, "") + vbCrLf)
                ElseIf selection.Text.Trim = "" Then
                    selection.Delete()
                End If
            End If
            selection.LineDown()
            selection.LineDown()
            selection.EndOfLine()
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            DTE.Properties("TextEditor", "CSharp").Item("WordWrap").Value = wrCS
        End Try
    End Sub
End Module

Comments [1] | | # 
 Monday, May 12, 2008
Monday, May 12, 2008 3:20:09 PM (Mountain Standard Time, UTC-07:00) ( Programming )

I just completed a reorganizing of the solution that I am currently working on. I now have only 2 projects in the solution. I use to have 3 project:

  • {ApplicationName} - This contained the project for the application itself, all of the logical layers lived in this project.
  • {ApplicationName}.Test - The unit tests for the Application (integration and unit)
  • {ApplicationName.Build - All of the artifacts related to managing the build process

After the reorg that just took place over the last 1 hour it is now:

  • {ApplicationName} - Same as before, except now each spec/specs live beside the code it is testing.
  • {ApplicationName}.Build - Same as before

Thanks to the power of ReSharper and an existing NAnt build file that I was already using to manage the project build/compilation/test ... It took me 40 minutes to do the file shuffling. ReSharper helped out with the namespace changes. 3 lines of xml added to the build script (no other changes required) and I am back in business!!

I love ReSharper!! And yes, I am running the latest nightly build (797) and it has been running amazingly. I currently have Solution Wide Error Analysis turned off, as it seems to slow things down a little.

Comments [7] | | # 
 Friday, May 02, 2008
Friday, May 02, 2008 7:04:51 PM (Mountain Standard Time, UTC-07:00) ( Programming )

I am currently trying to add some polish to the application that I am working on, and I stumbled upon this post here that pointed to a location that contained a zip file with a majority of the standard icons that Microsoft uses in both Visual Studio and the Office Suite. For those of you running Visual Studio 2008 you can find the zip file in the following location:

C:\%vs install path%\Common7\VS2008ImageLibrary\1033

In that folder you will find a zip file named: VS2008ImageLibrary.zip.

Just extract the contents of that zip file and you have more icons that you can probably work with!!

Develop With Passion!!

Comments [3] | | # 
Friday, May 02, 2008 2:01:15 PM (Mountain Standard Time, UTC-07:00) ( Agile | Programming )

I was in the gym this morning (at one point I will write a whole post on a good exercise routine for those of you who are curious) and I was just about to finish the bench press. As I place the bar back up on the rack I realized that I probably had a little more in me, but I lacked the aid of a spotter who could provide me with a bit of incentive/support in the event that I would not be able to get another rep out.

This got me thinking about the term spotting. Here are a couple of quotes about spotting taking from the wikipedia definition:

"Spotting, in weight or resistance training, is the act of supporting another person during a particular exercise, with an emphasis on allowing the participant to lift or push more than he could normally do safely."


Correct spotting involves knowing when to assist with a lift and encouraging a training partner to push beyond the point in which they would normally 'rack' (return the weight to its stationary position) the weight....."


This actually got me thinking about the pair programming process and the concept of being a spotter in the software development realm. When two people are actively pairing on a problem there is usually only 1 person who is typing while the other person is observing and conversing with the person doing the driver. The person not typing is not there in a passive or static role. They are


"actively supporting another person during the programming exercise"


They will be:

  • Catching potential design flaws the person driving may be missing
  • Providing ideas to a "driver" who may be stuck without an idea of how to go forward
  • Positively criticizing code choices that will result in a maintenance issue a couple of minutes from now (compounded if you add 6 months on top of that). Things such as cryptic variable names, class names that do not fit with the domain or problem space being tackled, long methods...
  • Taking the weight (keyboard) from the person entirely if they are completely unable to move forward

I think the last sentence in the wikipedia description is interesting:

"As a general rule to prevent injury and ensure safety spotters should have the strength to be able to control the weight should their training partner's strength completely fail. This is known as a "bail out"."

When two programmers who are at a similar skill level get together to pair program a design problem, it provides a lot of stimulation, challenge, and idea bouncing that may not have happened had there been significant gaps in the skill level between the 2 developers. It also provides the added benefit of the "bail out" when the person driving the problem out in code gets stuck and they fail to keep moving forward, they can pass of the reigns to their pair while they regain their mental composure to tackle the problem once more.

Most of us know that it is a bad idea to attempt a heavy bench press without the aid of someone to spot us. In the same way, when you are facing down a particularly difficult challenge would you not prefer to have a spotter to aid you through the process?

Develop With Passion!!

Comments [1] | | # 
 Tuesday, April 15, 2008
Tuesday, April 15, 2008 3:59:41 AM (Mountain Standard Time, UTC-07:00) ( Programming | Tools )

For the last couple of weeks, I have been integrating Vim and a complementary set of tools into my development toolkit. I am firmly on board with what the pragmatic programmers say:

"Learn a good editor, and learn it well!!"

I am thoroughly impressed with Vim, Viemu etc. Last week I was recommended a registry hack that would allow my Caps Lock key to have the same behaviour as the ESC key. This results in a much smoother experience when using Vim.

So far, I am loving the reg hack and much prefer the need to not have to move my hand to hit the ESC key. Here is the text of the reg file:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout]
"Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,01,00,3a,00,00,00,00,00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout\DosKeybCodes]
"00000804"="ch"
"00000408"="gk"
"00010408"="gk"
"00020408"="gk"
"00050408"="gk"
"0001041f"="tr"
"0000041f"="tr"
"00000423"="us"
"00000402"="bg"
"00000419"="ru"
"00010419"="ru"
"00000c1a"="us"
"00010c1a"="us"
"00000422"="us"
"00010402"="us"
"00020402"="bg"
"00030402"="bg"
"00020422"="us"
"00000412"="ko"
"00000425"="et"
"00000426"="us"
"00010426"="us"
"00000427"="us"
"00000411"="jp"
"00000404"="ch"
"0000041C"="us"
"0000041a"="yu"
"00000424"="yu"
"00000405"="cz"
"00010405"="cz"
"0000040e"="hu"
"0001040e"="hu"
"00000415"="pl"
"00010415"="pl"
"00000418"="ro"
"00010418"="ro"
"00020418"="ro"
"0000041b"="sl"
"0001041b"="sl"
"00000442"="tk"
"00000813"="be"
"0000080c"="be"
"00001009"="us"
"00000c0c"="cf"
"00010c0c"="cf"
"00000406"="dk"
"00000413"="nl"
"0000040b"="su"
"0000040c"="fr"
"00000407"="gr"
"00010407"="gr"
"0000040f"="is"
"00001809"="us"
"00000410"="it"
"00010410"="it"
"0000080a"="la"
"00000414"="no"
"00000816"="po"
"00000416"="br"
"0000040a"="sp"
"0001040a"="sp"
"0000041d"="sv"
"0000100c"="sf"
"00000807"="sg"
"00000809"="uk"
"00010409"="dv"
"00030409"="usl"
"00040409"="usr"
"00020409"="us"
"00000409"="us"
"00000452"="uk"
"0000046e"="sf"

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout\DosKeybIDs]
"00010408"="220"
"00020408"="319"
"0001041f"="440"
"0000041f"="179"
"00010415"="214"
"00000442"="440"
"00000410"="141"
"00010410"="142"

Create a reg file and copy the contents into it, then merge the file into your registry. Make sure that you want to not have normal use of your caps lock key.

Develop With Passion!!

Comments [11] | | # 
Tuesday, April 15, 2008 3:48:56 AM (Mountain Standard Time, UTC-07:00) ( Programming )

Ever since I received the BDD test naming macro from Scott Bellware last year, it has gone through several iterations of improvements (mostly due to students taking the time to tune up the macro).

Of all of the enhancements to the macro, none of them have done as much for the speed of the macro of the enhancements made by:

Todd Berry and Casey Gum

The macro now runs so fast that it is a joy to watch (you have to be quick). For those of you who are switching to leveraging context style BDD testing, you may want to pick up the macro and integrate it into your IDE:

 

Imports System

Imports System.Windows.Forms
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics

Public Module CodeEditor

    Public Sub ReplaceSpacesInTestNameWithUnderscores()
        If DTE.ActiveDocument Is Nothing Then Return
        Dim wrCS As Boolean = DTE.Properties("TextEditor", "CSharp").Item("WordWrap").Value

        Try
            DTE.Properties("TextEditor", "CSharp").Item("WordWrap").Value = False
            Dim selection As TextSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection)
            Dim index As Integer

            selection.SelectLine()
            If selection.Text = "" Then Return

            Dim methodIndex As Integer = selection.Text.IndexOf("public void ")
            Dim classIndex As Integer = selection.Text.IndexOf("public class ")

            If (methodIndex < 0 AndAlso classIndex < 0) Then Return

            index = CType(IIf(methodIndex >= 0, methodIndex, classIndex), Integer)

            Dim prefix As String = CType(IIf(methodIndex >= 0, "public void ", "public class "), String)
            Dim whiteSpace As String = selection.Text.Substring(0, index)
            prefix = whiteSpace + prefix
            Dim description As String = selection.Text.Replace(prefix, String.Empty).Trim
            Dim text As String = prefix + description.Replace(" ", "_").Replace("'", "_") + vbCrLf
            selection.Delete()
            selection.Insert(text)
            selection.LineUp()
            selection.LineUp()
            selection.SelectLine()
            If selection.Text.Trim = "{" Or selection.Text.Trim = "}" Or selection.Text.Trim = "" Then
                If selection.Text.Trim = "{" Or selection.Text.Trim = "}" Then
                    selection.Insert(selection.Text.Replace(vbCrLf, "") + vbCrLf)
                ElseIf selection.Text.Trim = "" Then
                    selection.Delete()
                End If
                selection.Insert(whiteSpace + IIf(methodIndex >= 0, "[Test]", "[TestFixture]") + vbCrLf)
            End If
            selection.LineDown()
            selection.LineDown()
            selection.EndOfLine()
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            DTE.Properties("TextEditor", "CSharp").Item("WordWrap").Value = wrCS
        End Try
    End Sub
End Module

 

Develop with Passion!!

Comments [4] | | # 
 Wednesday, December 19, 2007
Wednesday, December 19, 2007 10:26:48 PM (Mountain Standard Time, UTC-07:00) ( C# | Programming )

Got some feedback on my MappingEnumerable post. People wanted to see me leveraging some of the new language features (specifically linq).

I can leverage linq to change the extension method to eliminate the need for the MappingEnumerable (which was brought in to mitigate the absence of extension methods) and replace it with the following code: 

public static IEnumerable<Output> MapAllUsing<Input,Output>(this IEnumerable<Input> items,IMapper<Input,Output> mapper) { return from item in items select mapper.MapFrom(item); }

K. Scott Allen had the suggestion to use property initializers:  

IEnumerable<Department> departments = departmentRepository.GetAllDepartments(); return from d in departments select new DepartmentDisplayItemDTO() { ID = d.ID, Name = d.Name };

Which you can definitely do if you so wish, that specific dto is completely immutable so the above would not work, but could be changed to accommodate.

It is important to note that the IMapper<Input,Output> interface is an interface that can be implemented to perform all sorts of mapping. Some examples of how I have used this in the past are:

  • Mapping from DB to Domain
  • Mapping from Domain to DTO
  • Mapping from Errors to ScreenElements
  • Mapping from DTO to Presentation Model
  • ….

You are only limited by your imagination. And because each mapper has a single MapFrom method, it is very easy to test specific implementations of the interface, you can even create a non generic IMapper interface that you can use for completely reflective scenarios (picture externally defined OO mapping).

K. Scott Allen also mentions DTO Tax, and I don’t think his point is specific to just DTO’s but the cost of mapping in general. Focusing on 1 mapping at a time, refactoring out the duplication and moving on; is a way that you can grow and add all sorts of mapping in a very organic way to your applications.

Develop With Passion!!

Comments [3] | | # 
Wednesday, December 19, 2007 1:44:14 PM (Mountain Standard Time, UTC-07:00) ( C# | Programming )

With a newfound interest in leveraging the AutoMockingContainer (credit to James for convincing me of this approach) here is the code for my base class used to write BDD style interaction based tests:

public abstract class Specification { private MockRepository mockery; private AutoMockingContainer container; protected MockRepository Mocks { get { return mockery; } } protected AutoMockingContainer Container { get { return container; } } [SetUp] public void BaseSetup() { mockery = new MockRepository(); container = new AutoMockingContainer(mockery); container.Initialize(); Before_each_spec(); } [TearDown] public void TearDown() { After_Each_Spec(); } protected virtual void After_Each_Spec() { } public IDisposable PlayBackOnly { get { using (Record) { } return PlayBack; } } public void BackToRecord(object mockObject) { Mocks.BackToRecord(mockObject); } public IDisposable Record { get { return Mocks.Record(); } } public IDisposable PlayBack { get { return Mocks.Playback(); } } public abstract void Before_each_spec(); public Item CreateSUT<Item>() { return container.Create<Item>(); } public Interface CreateStrictMockOf<Interface>() { return mockery.CreateMock<Interface>(); } public IEnumerable<T> CreateMockEnumerable<T>() { return CreateMock<IEnumerable<T>>(); } public T Mock<T>() where T : class { return container.Get<T>(); } public void ProvideAnImplementationOf<Interface, Implementation>() { container.AddComponent(typeof (Implementation).FullName, typeof (Interface), typeof (Implementation)); } public void ProvideAnImplementationOf<Interface>(object instance) { container.Kernel.AddComponentInstance(instance.GetType().FullName, typeof (Interface), instance); } protected Interface CreateMock<Interface>() { return Mocks.DynamicMock<Interface>(); } }

I changed some of my original method names to match up with what Dave was doing (for a bit of consistency).Here is an example of a testfixture that leverages this as the base (this test happens to use an explicit CreateSUT method, vs the one provided by the AutoMockingContainer):

 

[TestFixture] public class When_told_to_visit_all_items : Specification { private IVisitor<int> visitor; private RichList<int> numbers; private IEnumerableActions<int> sut; private IEnumerableActions<int> CreateSUT() { return new EnumerableActions<int>(numbers); } public override void Before_each_spec() { numbers = new RichList<int>(); numbers.Add(1); numbers.Add(2); sut = CreateSUT(); visitor = CreateMock<IVisitor<int>>(); } [Test] public void Should_tell_visitor_to_visit_all_items_in_the_enumerable() {