I’ve been working with OzCode for some time now, and every now and then I find a cool capability I didn’t know it had.
Today I wanted to investigate (read: debug) the way several objects were xml-serialized for a demo I’m preparing and for that I created the following method:
static class Xml
{
    public static string SerializeObject<T>(this T toSerialize)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());

        using (StringWriter textWriter = new StringWriter())
        {
            xmlSerializer.Serialize(textWriter, toSerialize);
            return textWriter.ToString();
        }
    }
}
Now I could use the immediate window to serialize a few classes by calling it:

CustomXmlSerialize
As you might have guessed I needed to do quite a lot of scrolling and copy-pasting in order to understand this long line of xml.
Since I also needed the value for debugging I decided to try and use Custom Expressions – and it worked!
By using OzCode’s “magic wand” to create a new Custom Expression that called the new method, I got a “new” property in my object that has the full XML serialization result.
OzCodeCustomExpressionXmlSerialize
Keep in mind that it won’t work when debugging code that cannot access the method used and I recommend using the fully qualified method name (with namespace). And remember – there’s serialization code running underneath the new “property” – so consider deleting the expression once you finish using it (it can always be added back).

With this new property I was able to finish debugging several objects without stopping mid-debug to add code that had no business being there.

Happy coding (&debugging) …

Did you know that Visual Studio shows deadlocked tasks?

No comments

Wednesday, December 30, 2015

I didn’t…
And it’s not a new feature – since it existed since freaking Visual Studio 2010!
Yesterday during an unrelated meeting Alon Fliess showed a bunch of us developers how Visual Studio detects deadlocks in tasks (automatically) and shows the current task status in both Parallel Tasks and Tasks debug windows (duh).
I got home late but I wanted to experiment and see what would happen and so I wrote a simple program to see how well Visual Studio understands the bugs I can trough at it:
static void Main(string[] args) 
{ 
    int taskCount = 6; 
    var tasks = new Task[taskCount]; 
    var autoResetEvent = new AutoResetEvent(false); 
    for (int i = 0; i < taskCount; i++) 
    { 
        tasks[i] = Task.Factory.StartNew(state => 
        { 
            var index = (int)state; 
            if (index < 3) 
            { 
                tasks[(index + 1) % 3].Wait(); 
            } 
            else if (index == 3) 
            { 
                Task.Factory.StartNew(() => 
                { 
                    while (true) { } 
                }).Wait(); 
            } 
            else 
            { 
                autoResetEvent.WaitOne(); 
            } 
        }, i); 
    } 

    Task.WaitAll(tasks); 

    autoResetEvent.Set(); 
}
What a mess – I have three tasks waiting on each other (deadlocked), two more tasks waiting indefinitely on a AutoResetEvent and one task that starts yet another task that runs an infinite loop (just for fun).
After a few seconds I paused/breaked execution and got the following (Debug –> windows –> Tasks):
image
So out of the 6 tasks I spawned the first three deadlocks are detected by VS, Three tasks that show as blocked (waiting for AutoResetEvent and waiting for another task to complete). The only task that shows as running is the one that happily burning CPU on a while loop that would never end (also known as the Halting problem).
That’s good enough for me.
I guess it’s another case of a useful feature that I always wanted but didn’t know already existed.

Happy coding…

VS2015 Update 1 brings (back) parallel test execution

2 comments

Friday, December 04, 2015

Yesterday I’ve installed the new VS2015 update and tried to make my machine talk to my win10 (IoT core) Raspberry PI. It didn’t help but that’s a story for another blog post – spoiler: it was a problem with my laptops Ethernet port.

After the dust settled I’ve started reading about the new goodness that was just added to my trusty Visual Studio and found out that Microsoft has decided to give us the parallel test execution.

It all started back in the long forgotten Visual Studio 2010. Back then we had a great feature called parallel test execution. It did exactly that – reduce run speed by utilizing several cores to run tests – it was well hidden but for those of use who know where to enable it – it worked like a charm - as long as other tools, especially your Mocking framework of choice supported multi threading.

Then came VS2012 and the ability to run unit tests side by side disappeared… you could use it but for the price of using the old soon to be legacy test runner.

Since I liked the fact that my test run took less time I was happy to see that the feature I liked came back.

Enabling parallel tests is simple – first create a new test.runsetings – don’t look for a template (because there is none), just add a new xml file and rename it.

For parallel tests you just need the file to contain the following lines:


<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<RunConfiguration>
<MaxCpuCount>0</MaxCpuCount>
</RunConfiguration>
</RunSettings>

For the value of MaxCpuCount  use the number of threads you want to use (usually 1 for sequential run), or instead ‘0’ or a number greater of the number of your machine logical core (please use ‘0’).

Look under Test menu for “Select Test Settings File” and choose the newly minted (test settings) file.

image

For more information of what the test settings file can do for you – read this MSDN page.

Now when running the tests you’ll see improvement it the time it takes for them to finish.

mstest_parallelUntitled

I did notice that it took longer for the tests to start running and there’s a barely noticeable delay at the end of the run but other than that – parallel tests!

As you can see the runner runs assemblies in parallel so if you have a lot of tests in one assembly – you might not benefit from this feature, please consider splitting your tests (and probably production code as well).

I still need to check if (and which) mocking frameworks would work with this new(ish) test execution.

 

Happy coding…

When Mockito’s InjectMocks does not inject mocks

3 comments

Thursday, November 26, 2015

Looking back at the time wasted yesterday while trying to make a trivial functionality work makes me wonder if it was a good idea to begin with…

It all started  (and ended) yesterday while I was mentoring a team on the fine art of Java unit testing.

We’ve decided to use Mockito’s InjectMocks due to the fact that most of the project's classes used Spring to fill private fields (don’t get me started).

For those of you who never used InjectMocks before – in the Mockito word we can auto-magically initialize and inject mock objects into the class under test. And it’s all done using annotations.

And so if I have the following class:


public class MyClass {

@Resource
private INetworkService networkService;

@Resource
private IFileService fileService;

public boolean SomeMethod(){
// some logic here

// More logic here
networkService.Send();

return true;
}
}

I can write a test fixture that looks like this:


@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@Mock
private INetworkService networkService;

@Mock
private IFileService fileService;

@InjectMocks
MyClass myClass;

@Test
public void testSomeMethod() {
boolean result = myClass.SomeMethod();

assertTrue(result);
}
}

And so the two dependencies (marked with @Mock) would be faked and inserted into MyClass by constructor, property or field injection.

The problem was that we couldn’t get it to work. The mocks were initialized and the class was created - without the dependencies. It took us some time but finally we’ve found the reason: the real class looked something like this - can you spot the difference?


public class MyClass {

@Resource
private INetworkService networkService;

@Resource
private IFileService fileService;

private Integer version;

public MyClass(Integer version) {
this.version = version;
}

public boolean SomeMethod(){
// some logic here

// More logic here
networkService.Send();

return true;
}
}

Did you see it?

In our real class we had a non-empty constructor which InjectMocks tried to use, but passed null since Integer canno be mocked by Mockito (it’s a final class). Once Mockito found a constructor to try and to use it didn’t even try to inject the two fields (lazy bastard). And so the dependencies inside the MyClass remained null causing a null reference exception to be thrown once used.

It’s not that Mockito guys didn’t do a good job, this behavior is documented – which makes it yet another case of RTFM.

The problem is that the tests who successfully run using this mechanism could one day fail just because someone decided to add another constructor…

 

Happy coding

I’m going to have a good time in the next couple of months – I have several interesting speaking opportunities right around the corner:

agileTD

In less than two days I’ll be traveling to Germany to attend AgileTD. This is my first time at that AgileTD but from what I hear it’s an amazing conference. This year there are several ATDD/BDD talks which I plan on attending – as well as contribute to, since on the last day I get to speak about A/T/B/DD in Navigating the xDD alphabet soup.

codcemotion

The next conference is on my home turf – CodeMotion is coming to Tel Aviv and I get to speak about unit testing mistakes and misunderstanding in 5 unit testing facts I wish I know 7 years ago.

ndclondon

This is the third time I get invited to speak at NDC London – one of the best conference I got to speak at with excellent speakers. This time I have something different in store - I’m going to do a session on Electronics 101 for software developers.

 

That’s it for now – wish me luck, and if you’re around – come over and say hello.

Using C++ debug visualizers in VS2015

No comments

Thursday, October 22, 2015

I have been using the .NET debug visualizers (and DebuggerDisplay atribute) for a long (long) time and I like the way they make my code easy(ier) to debug. Until recently I was not aware that Visual Studio has a similar capability for C++.
Any C++ dev armed with Visual Studio can use XML files to create debug visualizers, In Visual Studio 2015 there’s no longer a need to to deploy these visualizer on each on each developer machine – just add the new, easy to write visualizer to your project and your team gets to automatically use it via the magic of source control.
Consider the following class:

class Customer
{
 int m_id;
 string m_firstName;
 string m_surname;
 int m_age;
 Gender m_gender;
 string m_emailAddress;
 string m_telephoneNumber;
 Address m_address;

 // ...
};

In order to use a debug visualizer just add a new natvis file - Add new Item and choose the Debugger visualization file (.netvis) template.
image
And presto - a new debug visualization file would be added to your project.
After a little tinkering I’ve created the following:

<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
  <Type Name="Customer">
    <DisplayString>Name: {m_firstName}</DisplayString>
    <Expand>
    <Item Name="Id">m_id</Item>
    <Item Name="Gender">m_gender</Item>
    <Item Name="Age">m_age</Item>
    <Item Name="Address">m_address</Item>
    </Expand>
  </Type>
</AutoVisualizer>

Which was really simple to write:
  • To display the customer’s name automatically I’ve added DisplayString with “Name:” and the value in curly brackets.
  • Right now I only care about four of the customer’s fields so I’ve added Expends with those fields
And I got the following in my watch window:
image
Which is nice but not great – I would like to see the customer full name and so I’ve tweaked DisplayString a bit:

<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
  <Type Name="Customer">
    <DisplayString>Name: {m_firstName, sb} {m_surname, sb}</DisplayString>
    <Expand>
    <Item Name="Id">m_id</Item>
    <Item Name="Gender">m_gender</Item>
    <Item Name="Age">m_age</Item>
   <Item Name="Address">m_address</Item>
    </Expand>
  </Type>
</AutoVisualizer>

And I did it during a debug session – seeing the results each time I save the natvis file:
CppDebugVisulaizer1
I’ve used Format specifier (that’s the “sb”) to remove the quotes and make the name more human readable. In fact I can use another formatter for Gender – en (for Enum).
I would also like to make the customer address visible in the display string. Since Address is a class I’ll first define a visualizer for it (blow the customer visualizer) and update the customer visualizer to use the address as part of the display string:

<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
  <Type Name="Customer">
    <DisplayString>{m_firstName, sb} {m_surname, sb} [{m_address}]</DisplayString>
    <Expand>
      <Item Name="Id">m_id</Item>
      <Item Name="Gender">m_gender, en</Item>
      <Item Name="Age">m_age</Item>
      <Item Name="Address">m_address</Item>
    </Expand>
  </Type>
  <Type Name="Address">
    <DisplayString>{m_streetAddress, sb}, {m_city, sb}, {m_country, sb} Zip:{m_zipCode}</DisplayString>
  </Type>
</AutoVisualizer>

This doesn’t seem much – but in order to get similar behavior in .NET I’ve needed to use OzCode – since nested/recursive DebugDisplayAttribute is not supported in .NET.

Conclusion

There are other nifty debug visualizer related features in VS2015 but I find the ease of use and deployment to be the real game changer.
Now when I get to look at big vector of Customers without needed to expend and find what I want:
image
As simple as that.

Happy coding (Even in C++)…

What are you waiting for???

No comments

Sunday, October 04, 2015

The contract has been signed, the training finished and all the company is ready to start using the best development practices known to man - unit testing, TDD, Clean code, pair programming you name it! But there’s just one problem preventing the change from happening...
Or as the good doctor puts it:
You can get so confused that you’ll start in to race down long wiggled roads at a break-necking pace and grind on for miles across weirdish wild space, headed, I fear, toward a most useless place.
[Excerpt from Oh, The Places You’ll Go! by Dr. Seuss]
What could be this place which you ask? It’s the “we don’t have time now – let’s do it later” place.
I usually can see it coming a mile away. After initial work has been done, and the team is waiting to start the next stage/iteration. I get a talk from the team leader/manager/developer and he would tell me that xyz is a good idea, one which we would definitely use once we release the current version
I remember one developer tell me that he’s going to start using TDD when developing the next feature - over the course of a year (in which he implemented countless features).
Sometimes the team need the conditions to be just right – enough time (which you’ll never get), the right person to come back from vacation (and would have enough time between answering his emails and catching up with work?), some developers are waiting for permission (to do refactoring? or write unit tests - why not ask for permission to use integers instead?) - in this point I expect someone to tell me that he need to wait for the next moon eclipse so he can invoke the old gods and make sure that the new code would work.
But all these reasons (read: excuses) have one thing in common – they all make sure that we’re not leaving our warm and fuzzy comfort zone.
The Waiting Place…for people just waiting.
Waiting for a train to go or a bus to come, or a plane to go or the mail to come, or the rain to go or the phone to ring, or the snow to snow or waiting around for a Yes or No or waiting for their hair to grow. Everyone is just waiting.
Waiting for the fish to bite or waiting for wind to fly a kite or waiting around for Friday night or waiting, perhaps, for their Uncle Jake or a pot to boil, or a Better Break or a string of pearls, or a pair of pants or a wig with curls, or Another Chance. Everyone is just waiting.
[Excerpt from Oh, The Places You’ll Go! by Dr. Seuss]


And I’ve seen it happen countless times. It always comes down to – good idea, we defiantly need it, not now…
I really don’t understand the big deal with waiting – every single change in your code can be reverted (can has source control?) and you should be able to verify that your code works (if not make plans to fix that– quick). I’ve seen teams refuse to make a change that would reduce the amount of work they do (not to mention improve quality) and keep working twice as hard instead.64866203
Instead break the cycle – ask yourself: “how can I make sure that tomorrow I won’t make the mistakes I did today”. Try something new – you have absolutly nothing to loose.
No! That’s not for you!
Somehow you’ll escape all that waiting and staying. You’ll find the bright places where Boom Bands are playing. With banner flip-flapping, once more you’ll ride high! Ready for anything under the sky.
[Excerpt from Oh, The Places You’ll Go! by Dr. Seuss]


Happy coding…



Related Posts Plugin for WordPress, Blogger...
Top