Upcoming speaking engagements: Vancouver here I come!

No comments

Monday, November 14, 2016

At the beginning of December I’m going to speak at ConFoo Vancouver.
Vancouver 2016 | December 5-7, 2016
I spoke at ConFoo Montreal in the past and I look forward to speaking at the first ever ConFoo Vancouver.
I’ll be speaking on two of my favorite topics – unit testing and electronics (not at the same session).
5 Unit Testing Facts I Wish I’d Known 7 Years Ago – on Tuesday (6th) . A session I’ve created as a kind of retrospective of what worked, and especially what didn’t work when I attempted to start unit test my code. I wanted to provide a few tips for software developer starting down the unit testing path so that they won’t fail just like I did oh so many years ago.
Electronics 101 for Software Developers – on Wednesday (7th). A fun session for all developers who want to start building cool IoT/electronics projects. I plan to start from the basics of electricity and explain how to use sensors and read circuit diagrams – it would be fun, informative and useful for anyone who ever wanted to build his own robot army:
WP_20161018_12_45_05_Pro
Before all that on Monday night (5/12) I’m going to speak at the Windows Platform Developer Group with Ariel Ben Horesh.
We’re going to do a two part meetup – I’ll talk about Visual Studio debugging tricks every .NET developer should know and Ariel is going to discuss how to build your company’s mobile development strategy in “Calling the Shots: Should I go Native or Cross Platform?
If you’re interested in learning how to quickly and effectively debug your code you should come – especially since you might receive an OzCode license.

So if you’re living in Vancouver or you’re just in town for ConFoo – come by and say hello.

With every new version the C# language has grown and improved. The last version so a.k.a C# 6 has brought some of my favorite features. And with C# 7 just around the corner I know there's more to come.

One of the new useful features added to C# is the ability to filter exceptions. Consider the following - completely (and poorly) invented class:

public class MyClass 
public class MyClass
{
    public void MyMethod(int count)
    {
        throw new MyException(1000 + count);
    }
}

If I need to exit only when an exception with a specific error code is thrown I can write the following code:

class Program
{
    static void Main(string[] args)
    {
        var myClass = new MyClass();

        for (int i = 0; i < 10; i++)
        {

            try
            {
                myClass.MyMethod(i);
            }
            catch (MyException ex) when (ex.ErrorCode == 1003)
            {
                Console.WriteLine($"Got the right exception in iteration: {i}");
                break;
            }
            catch (MyException ex)
            {
                Console.WriteLine($"Other exception: {ex.ErrorCode}");
            }
        }
    }
}

And each exception with value which is not 1003 will be swallowed. There are limitless scenarios in which this feature can be useful - for example have a look at Jimmy Bogard's post on how to avoid exceptions on the weekends.

But what happens when I need the same functionality but just for a specific debug session or if I'm working on a project which does not use C# 6 (yet?). For those cases I can use the magic of conditional breakpoints.

Filtering with conditional breakpoints

There are two ways to set a conditional breakpoint - the old way and the OzCode way.

If you never used them - you should; it's a time saving tool which will save you valuable debug time.

In order to use Conditional breakpoints just create a regular breakpoint at the exception's constructor and then add condition to that breakpoint - simple as that. With OzCode it's even easier:

  1. Create a "regular" breakpoint at the exception's constructor
  2. Run until breakpoint
  3. Open the quick watch window
  4. Choose the property you care about
  5. Update the condition
  6. Press "ok" and run

 

Conditional_breakpoints

Once you fix the bug you can delete the conditional breakpoint and continue working – or find and fix another bug.

Conclusion

Conditional breakpoints have been part of your favorite IDE of choice for ever and yet not all developers use them as often as they should. Catching just the right exception is one scenario where they help find and fix bugs and save us time in which we can develop new features for our customers or just grab another cup of coffee.

Faking DateTime using Microsoft Fakes seems to be broken

No comments

Tuesday, November 08, 2016

It seems as if causing DateTime.Now to return another value has become the demo to show when demoing an unconstrained Mocking framework. It’s easy to show and needed in many unit tests – unless you want your tests to be affected by time – trust me and you don’t.
That’s why I was amazed to find out that the demo from MSDN which showed how to use Shims has somehow stopped working…

What I initially did

In order to start using Microsoft Fakes you need to use Visual Studio Enterprise edition – I’ve used VS2015 update 5 in this case.
The next step is to right click on the assembly you need to fake and choose Add Fake Assembly
image
this will generate the same assembly followed .fakes so if you’re faking MyAssembly a new MyAssembly.Fakes will be created this is not the case with System as I was quickly reminded.
Now according to my knowledge and the demos at hand all I needed to do now is find ShimDateTime and use some magic to change how it behaved – but it was no where to be found – in fact I could not see anything to do with DateTime which I know for certain existed inside System.
It took me a while to get it but looking at the project’s references showed the problem:
image
You see – usually when faking System two fake assemblies are created – one for System and one for mscorlib where the good stuff is.
You can even see that under Fakes folder there are two configuration files one for each – but no mscorlib to be found.

The Solution?

I did what any developer would have done: I’ve decided to repeat the same process again expecting different results. Actually first I Googled a bit and found very little information.
And so I need to delete three files – the fakes assembly and two configuration files (fake configuration?) and try again – and I got the exact same mess.
After trying two more time – just to make sure I’ve decided to check the output window and saw the following:
image
Armed with this new knowledge I’ve decided to dig into some documentation and found that some new breaking changes caused issues when creating fakes and quick workaround would be to remove a few classes from the To fake list” and so I’ve opened mscorlib.fakes configuration file and written (read: pasted) the following code:
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
  <Assembly Name="mscorlib" Version="4.0.0.0"/>
  <StubGeneration>
    <Remove FullName="System.Diagnostics.Tracing"/>
    <Remove FullName="System.Text.Encoding"/>
    <Remove FullName="System.Security.Cryptography" />
  </StubGeneration>
</Fakes>
Next I’ve deleted System.4.0.0.0.Fakes and system.fakes and right-clicked System->Add Fakes Assembly and got the following:
image
And now I was able to write my test using my DateTime of choosing.

Frustrating? you bet! but at least now I know a quick workaround and able to test time based code – if all I have is Microsoft Fakes.
Last week my very first Pluralsight course went live!
image
My course on unit testing in C++ using CATCH is ready for your viewing pleasure. It’s about a topic I’m passionate about - how to write good unit tests, I’ve used Catch because I found that it helps writing good tests while avoiding many of the pitfalls that unit test practitioners might stumble on.
It was cool seeing the result of several months (more if you count the audition) of work.
Writing unit tests is a big part of being a professional software developer. This course would teach you how to write readable and robust unit tests using Catch, a simple, yet powerful unit testing framework.


I like to thank the good people of Pluralsight for helping me create this course and for the excellent feedback and all their hard work.
If you have any feedback or suggestion please let me know.

An open letter to conference’s organizers

No comments

Sunday, October 23, 2016

I got my first international speaking opportunity in 2012. After sending countless proposals and getting just as many rejects I got an email from DevReach telling me I got accepted – I remember reading it twice just to make sure. Speaking on DevReach was a big change from the user group talks I’ve done until then (and still do) – it was an amazing conference and I had the time of my life. Since then I’ve spoke at many other conferences and enjoyed every single one of them. However over the years I’ve noticed several things that some conferences did better than others – I’m not talking about the venue, number of speakers or the food/snacks but rather I’d like to focus on the relation between the single speaker and the conference’s organizers.

But first of all – if you’re a conference organizer I’d like to say one thing:

Thank you!

I’d like to say it again – thank you!

If you ever helped organize a conference – you’ve helped make our craft better and made a difference to countless other developers. You’ve labored for days (and nights) so that other practitioners of our craft can learn things that will make them better at their job while having a damn good time on top of that.

Thank you for providing a place to share ideas and learn new things – and if by chance you’re responsible for a conference I was fortunate to speak at – I will ever be in your debt (or owe you a beer).

Having said that, there are three things I’ve noticed some conference employ which I  wish all conference would do – I guess that the whole purpose of this post – and so without further ado let’s talk about the very beginning – how to find out about your conference: 

Please help me find out about your conference

As a speaker there is nothing more frustrating than finding out that you’ve just missed a conference’s CFP (Call For Papers) – that magical time in which you can submit talk abstracts to be considered, evaluated and even be selected as a fitting topic for that conference.

Some conference have a notification in place if you’ve already spoken at a conference in the past or it has a speaker mailing list. Otherwise a speaker needs to scan the internet with the hope of not missing another conference for the third time in a row. I do try, but I miss conferences CFP all the time even with good friends helping me catch CFPs, and following many twitter accounts as well as searching the internet on a monthly basis – I still find that catching the right conference is just too hard.

So if you want to make potential speakers lives easier – just create a mailing list and send us an email so we know when your conference is looking for speakers.

Make the speaker’s “benefits” known upfront (I.e. reimbursement)

Some conferences offer travel and/or hotel reimbursements while other offer different forms of compensation and some conferences don’t offer any – which is ok.

Not all conferences have the same budget – some have sponsors and ticket sales, while other are free and so cannot help the speaker with any travel or boarding costs - what you can or would provide your speakers it strictly up to you. All of this is well but the least you can do is let me know up-front.

The first thing I look for before submitting a few talks is if I’ll need to pay in order to speak, I need to be able to decide if the cost of travel and/or hotel on top of lost work days is worth speaking at your conference – if you let me know in time I might get an employer to cover some of the costs or even sponsor your conference, or I decide not to waste both our time.

In the last year I had to refuse a few speaking opportunities because the conference organizer notified me that I’ll need to cover my plane ticket only after my talk was already accepted and it was too late to do anything about it – other than cancel my appearance.

Help be become a better speaker (a.k.a feedback)

Everyone want to improve. If you’ve just rejected my session(s) – take a minute and tell me why. I used to send emails back to organizers asking what they did not like about my proposals – and gained a lot from their response. One conference which I like and respect did something even better – they post the reasons they have rejected your talks in your personal space on their site – so you get an explanation on how you can improve the next time you send session proposals.

Once a talk is over I like to talk with the audience to find out if they liked my talk and which parts they think were better and which should be tossed away. Some conferences do a good job of providing valuable, usable feedback as quickly as they can – and I wish I had proper feedback for each session I ever given.

Conclusion

This post is not a rant. Most of the conferences I spoke at over the years employed at least one of the practices mentioned  above. It’s all a matter of thinking about the speaker which in turn would help you make your conference great.

So if you’re planning a new conference or about to have the 99th year of an existing conference I wish you take the points I wrote about to heart.

And for the rest of you – the next time you go to an conference remember that someone worked hard to make sure you have a good time and be able to learn new cool things – and say thanks the organizers.

 

Until then – Happy coding…

MSTest V2 - First impressions

1 comment

Thursday, August 11, 2016

It’s been a while since I’ve tried a new Unit Testing framework. It seemed that between NUnit, XUnit & MSTest I had enough to choose from. I’ve always tried to be pragmatic when choosing a test framework for a new project and when suggesting one to a new client.

Although all .NET unit testing framework are pretty similar there are some differences between them – and I’m not talking about how they call the “Test” attribute.

It always frustrated me that MSTest didn’t seem to change much since it was introduced back in 2005 while both XUnit & NUnit have improved over time with new ideas that made unit testing easier to adopt.

One of the features I missed the most was Parameterized unit tests – the ability to write a test once and run it several times with the same input. Since MSTest is widely used it was frustrating to see good developers write bad tests just because that featured was missing.

Over the years I grow tired of waiting for that support and I’ve tried implementing it myself – with some success but without a lot of problems:

And then those solutions stopped working and I’ve stopped using them.

That’s why I was happy to find out that not only is Microsoft working on a new “MSTest V2” but it will have the parameterized tests I’ve always wanted.

On top of that getting started with it is simple. You no longer have the create a special “Unit Testing” project – any class library will do.

CreateClassLib

And Then just add MSTest.TestFramework & MSTest.TestAdapter using NuGet and you’re ready to go. (don’t forget to mark Include Prerelease)

nugettestadpater

nugetTestadapter

And writing tests just works just like before – even better now we have the ability to write tests with RowTests:

[TestClass]
public class TestFrameworkTest
{
    [TestMethod]
    public void SimpleTest()
    {
        Assert.IsTrue(false);
    }

    [DataTestMethod]
    [DataRow(1, 2, 3)]
    [DataRow(2, 2, 4)]
    [DataRow(3, 2, 6)]
    [DataRow(5, 2, 7)]
    public void RowTest(int a, int b, int result)
    {
        Assert.AreEqual(result, a + b);
    }
}

And it works! I run the tests and from each row runs as a separate test.

image

At the moment there is no way to run only one row – you have to run them all. This means that I cannot debug a single row – which can become very painful with multiple rows. Although NUnit (and XUnit) still have better row testing functionality at least now I can write (and teach how to write) proper tests even when a client has chosen to use MSTest (due to other good reasons).

Seems that MSTest is changing and I can’t wait to see what other new features will come next.

 

Until then – Happy coding…

Implementing Soundex using LINQ (with help from OzCode)

No comments

Wednesday, June 08, 2016

A while ago I came across the very interesting Soundex algorithm. It’s a way to find similarity between words based on how they sound – I’ll let Wikipedia explain:

Soundex is a phonetic algorithm for indexing names by sound, as pronounced in English. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling. The algorithm mainly encodes consonants; a vowel will not be encoded unless it is the first letter. Soundex is the most widely known of all phonetic algorithms (in part because it is a standard feature of popular database software such as DB2, PostgreSQL, MySQL, Ingres, MS SQL Server and Oracle) and is often used (incorrectly) as a synonym for "phonetic algorithm". Improvements to Soundex are the basis for many modern phonetic algorithms.

So basically Soundex can help you fix spelling mistakes by finding the word you meant to use based on how the words sound – so if you accidently search the internet for “Drawer Hellber” you’ll still be able find my blog:

image

Actually you won’t, but you get the point

It’s fairly easy to follow the steps of the algorithm (as defined by Wikipedia):

  1. Retain the first letter of the name and drop all other occurrences of a, e, I, o, u, y, h, w.
  2. Replace consonants with digits as follows (after the first letter):
    • b, f, p, v → 1
    • c, g, j, k, q, s, x, z → 2
    • d, t → 3
    • l → 4
    • m, n → 5
    • r → 6
  3. If two or more letters with the same number are adjacent in the original name (before step 1), only retain the first letter; also two letters with the same number separated by 'h' or 'w' are coded as a single number, whereas such letters separated by a vowel are coded twice. This rule also applies to the first letter.
  4. If you have too few letters in your word that you can't assign three numbers, append with zeros until there are three numbers. If you have more than 3 letters, just retain the first 3 numbers.

In a clear case of “When you have an hammer everything looks like a nail” I thought to myself – why not implement this algorithm in LINQ. And so I came up with the following code:

public string Encode(string word)
{
    if (IsNullOrEmpty(word))
    {
        return Empty;
    }

    return word
        .Select((ch, index) => EncodeCharacter(word, ch, index))
        .Where((encodedChar, index) => 
                    encodedChar.IsValidEncoding && encodedChar.Curr != encodedChar.Prev)
        .Select(arg => arg.Curr)
        .Concat(Enumerable.Repeat("0", MaxEncodedLength))
        .Take(MaxEncodedLength)
        .Aggregate((I, j) => I + j);
}

If you’re interested the entire Encoder.cs code file can be found here.

Although the algorithm seems simple enough, I had four bugs in my initial implementation but they were quickly squashed using OzCode with it’s new LINQ debugging feature (in the Early Access Preview). Now that I’ve got it working, I’m going to use OzCode to show you how the Soundex algorithm processes “Drawer” and “Dror” (one of which is not my name) and check that they both provide the same results.

Let’s start with “Drawer” – it should be encoded as D660.

Stopping the debugger at the beginning of the LINQ query shows us that indeed the result of the LINQ query is “D660” but it also shows us numbers at the end of each operator – those numbers indicate how many items were returned from each LINQ operator.

image

Looking at these numbers, I can tell that from the 6 characters in the beginning, only three were left after Where. The rest were either Invalid or the same as the letter before (rules 1-3). Then we concatenated 4 ‘0’ and then taken the first four characters (Take) and from there it was a simple case of aggreagating all of the letters into a single string.

Let see it step by step – using OzCode’s Detailed LINQ tool window:

Step 1: First letter saved and encode the rest of the letters according to rule #2 (‘*’ means invalid encoding):

image

As you can see, ‘D’ was kept and the two ‘r’s were encoded as ‘6’s while ‘a’, ‘w’ and ‘e’ were replaced with stars (invalid character).

Next we get rid of invalid & duplicate letters:

image

As you can tell by the red X’s all of the invalid characters were thrown away.

image

The Select is a simple conversion from my result type into simple strings.

With your permission I’ll jump directly to Aggregate where I stitch the strings together:

image

Simple.

In the case of “Dror” the result is similar

DrorSoundex

How cool is that?

If you want to find out more about OzCode and LINQ debugging – try the EAP, or better yet come to visit us at the OzCode booth at NDC Oslo – we’ve just landed and we plan on having a great week.

Related Posts Plugin for WordPress, Blogger...
Top