Blog Stats
  • Posts - 27
  • Articles - 0
  • Comments - 8
  • Trackbacks - 0

 

Tuesday, April 17, 2012

DevTeach Vancouver approaching fast !


Just a friendly reminder for people in the Vancouver area that DevTeach Vancouver is just a few weeks away !  Registration is open and I can't help but promoting a full day of TFS 2010 workshop given by Etienne Tremblay and myself plus we will most likely add extra material to cover for TFS vNext...  The four added topics will be:

Moving from TFS 2010 to TFS vNext

The Storyboarding addin for PowerPoint

Intellitrace in a Production Environment

Exploratory Testing

 

Also I'll be presenting a 1h session on mocking and mocking frameworks during the main event.  We'll compare Isolator, Justmock and Moq....

See you in Vancouver !

Monday, April 16, 2012

Coded UI Test Builder Visual Cues Offset


Wow it's been a long time since I posted anything in here.....

Today I'll be very brief because the subject is quite easy to cover but can be quite puzzling when it happens to you...  These days at work I'm exploring Coded UI Test in VS2010, Microsoft Test Manager 2010 and Microsoft Test Runner 2010 which is cool because I've been digging aroung VS2010 testing tools on my own since a year now and also started focusing on VNext's testing tools...  So when you automate a test you will most likely end up having to use the Coded UI Test Builder shown here  

When inspecting controls on your app with the little "Target" tool, you could be confronted to your controls being highlighted "in the wrong place" on your screen.  Kind of like there would be some sort of offset between the control you are pointing to and the visual rectangle cue created by the tool to say "here's the control I think you're pointing to"... Looking at the picture here you can see it's pretty anoying to point at a control, see the tool inspecting the right object but highlighting it lower and to the right of where the control actually is...  I have no clue if this only happens in WPF but here's the solution or at least what worked for me...  In my case I was using the "Medium - 125%" display setting in the personalization of my Windows 7 laptop...  The Coded UI Test Builder only works well when your display is set to 100% (smallest in my case).  Change that option to 100% and everything will start being highlighted at the right place in the tool...  I do think that this was intentionnal and that the tool was built to work only when using 100%...  What a shame but now you know so stop reading and go back to work !

Happy automating :)

Sunday, September 25, 2011

A full day of Azure conferences...


On October the 15th, the Montreal .NET User Group will hold a special event... a full day of conferences and workshops on Azure !  The speakers for the special event will be our very own Guy Barrette, Azure MVP, Sébastien Warin also and Azure MVP and Cory Fowler who just happens to be yet another Azure MVP !  Ain't that just amazing to see how many of them Azure MVPs we managed to pack in the same room for you to learn from?  All this for one low price... 10$....  and you have to be a registered and paid for member of the .NET Montreal User Group...

 

Circle the date on your calendar, Saturday October 15th, from 9am to 16h30pm at the UQAM university, room R-M110.

 

http://www.dotnetmontreal.com/events/25706911/

 

Cheers !

Friday, September 23, 2011

Dev Teach Ottawa approching FAST !


The long awaited Dev Teach conference approches FAST and will be held in Ottawa on nov the 2nd to nov the 4th!

Very interesting material both in the main event and in pre-conferences with 2 friends of mine, Laurent Duveau and Mario Cardinal both giving a pre-conference workshop !  For my part, I'll be giving a talk on Mocking and Mocking Frameworks as I really think people need to be more aware of their power and the fact that nowadays, effective, responsive, scalable unit testing inevitably equals mocking frameworks...  There is a grand total of 48 sessions planned for the event: 12 sessions by ITProTeach for IT Professionals, 12 sessions by SQLTeach for DBAs and finally 24 sessions by DevTeach for developers.

If you are in the area, you should definitly try to attend the conference.... 

 

Register today !

 

 

 

Tuesday, September 13, 2011

Vote for my talk at Techdays Montreal 2011 !!!


Techdays Montreal approches fast and will be held at the Palais des Congrès on november the 29th and 30th of 2011.

This year, the event content will be decided by you, the attendees !

You can vote for your favorite content here on a track by track basis and voting ends this FRIDAY the 16th !!!!

http://bit.ly/tdcan2011vote

Note that you do not need to fill every page to cast in your vote....  BTW I think they activated IP checking to prevent people from casting multiple votes so vote from HOME, not WORK... and if you vote for me then vote from HOME, WORK, CELL, GF's house, school  etc   :)   Mouhahah !

Please check out the session I'll give on MOCKING and vote for me if that's something you would like to see at Techdays 2011 Montreal !!!

 

Thanks ! 

Tuesday, March 29, 2011

Bridging the Gap - En Français à Québec le 14 Mai 2011 !!!!


Our 13 sessions are now available in english on :

Nos 13 sessions sont maintenant disponibles en anglais sur :

CHANNEL 9 !!!!

 

Bonjour à tous, l'événement "Bridging the Gap Between Developers and Testers Using Visual Studio 2010" sera également présentées LIVE le samedi 14 Mai 2011 à Québec.  Toute une journée de contenu "Real Life" gratuite, présentée par Etienne Tremblay et moi même en personne et EN FRANÇAIS.

 

Pour plus d'informations ou pour vous inscrire, veuillez vous référer au site de DevTeach

Monday, February 14, 2011

Bridging The Gap Between Developers And Testers With VS 2010


On January 29th Etienne Tremblay and I presented infront of roughly 120 people in Ottawa a 7 hours "sketch" on how VS 2010 and TFS 2010 can help both devs and testers in their respective work.  The presentation focused on how a testers' work can positively influence a developers' work and vice versa.  The format was quite unusual as I said it's a "sketch" where Etienne and I "ignore" the audience and we do as if we were at work and the audience is sort of "spying" on us.  In all I'm quite pleased with the content we presented and the format sure was alot of fun to render and I think the audience liked it too...  The good news for you people reading this post is that it got RECORDED and it's now available for download in quick 25 to 35 minutes format on the dev teach web site:

 http://www.devteach.com/ALM-TFS2010-Bridgingthegap.aspx

 

There were 2 cameras, one filming us and one capturing the screen for our demos.  We switch from one to another in an intersting flow and Jean-René Roy made sure he kept all our goofs and didn't edit those funny "oups moments" where we screw-up in the scenario...  Mostly educative but hilarious at times !!!

I encourage you all to download and watch the 13 episodes...  Follow a day at work for a tester and a developper using VS 2010 and TFS 2010 to improve their chemistry ! 

Thanks to Jean-René Roy for all the work he's put into this event and to Microsoft and Pyxis for sponsoring the event.

 

 

Sunday, January 30, 2011

Urban Turtle is such an awesome product !


Mario Cardinal, the host of the Visual Studio Talk Show, is quite happy these days. He works with the Urban Turtle team and they received significant support from Microsoft. Brian Harry, who is the Product Unit Manager for Team Foundation Server, has published an outstanding blog post about Urban Turtle that says: "...awesome Scrum experience for TFS.” You can read Brian Harry's blog post at the following URL: http://urbanturtle.com/awesome.

Thursday, November 25, 2010

Speaker at Tech Days 2010 in Montreal


Thanks to everyone who took part in Tech Days 2010 either as a speaker, attendee or else.

It was a great event where I got to present 2 sessions.  For everyone who might want to material for both sessions, here it is!

My guess is that the audio material should be available soon, on the microsoft tech days site...

 

Cheers

 

Tuesday, September 21, 2010

Conference at Vermont's Code Camp


Well, it's been a long time since my last post and unfortunately it's another simple thread to share my material but I'll resume posting here and there in the next couple weeks...

 

Here's the   link     to my presentation and supporting material which was about Lambdas and Extension Methods using Visual Studio 2010...  The powerpoint is there and so is the small project I used to demo my subjects...  There's also the source code for the Umbrella project...

Cheers !

 

Monday, May 31, 2010

Conference on LinQ at Montreal's ETS


Today I gave a presentation at Montreal's "Ecole de Technologies Supérieure" and I said I would put my presentation and the material itself online in here....  The audience was exclusively composed of teachers from colleges around Montreal. 

There's the link to download the content :

http://cid-bdf9cf467011e705.skydrive.live.com/self.aspx/.Public/LinQ%20at%20Montreal%5E4s%20ETS/LinQ.zip

 

I hope all attendees learned more on LinQ than they knew before!

 

 

Sunday, May 02, 2010

Tips on debugging collections


 

The "Quick Watch" feature of Visual Studio is an awesome tool when debugging your stuff...  I use it all the time and quite often I end up exploring hashtables or lists of all sorts...  One thing I hate is when I have to explore Collections...  Good god did I lose time trying to find the inner member that contains my stuff when exploring collections...  Most collections have the inside member that you can search for and find and explore to see the list of things you wanted to look at.  Something in the likes of this

 

I've known a little trick for a while now and I give it to everyone I end up debugging something with so I figured that probably not many people know about this...  Here's the tip...  Send the collection into an ArrayList in the QuickWatch window!  Yes, you heard me right, just type   

new ArrayList(yourcollectionhere)

in my case:    new ArrayList(this.Controls)

in the expresion textbox and here's the result when you hit reevaluate!

Pretty neat trick to make your debugging experience less of a pain when dealing with collections... 

 

Happy debugging all !

Saturday, April 24, 2010

Developing for 2005 using VS2008!


 
I joined a fairly large project recently and it has a particularity… Once finished, everything has to be sent to the client under VS2005 using VB.Net and can target either framework 2.0 or 3.0… A long time ago, the decision to use VS2008 and to target framework 3.0 was taken but people knew they would need to establish a few rules to ensure that each dev would use VS2008 as if it was VS2005… Why is that so? Well simply because the compiler in VS2005 is different from the compiler inside VS2008…  I thought it might be a good idea to note the things that you cannot use in VS2008 if you plan on going back to VS2005. Who knows, this might save someone the headache of going over all their code to fix errors…
-        Do not use LinQ keywords (from, in, select, orderby…).
 
-        Do not use LinQ standard operators under the form of extension methods.
 
-        Do not use type inference (in VB.Net you can switch it OFF in each project properties).
o   This means you cannot use VB.NET XML Literals.
 
-        Do not use nullable types under the following declarative form:    Dim myInt as Integer? But using:   Dim myInt as Nullable(Of Integer)     is perfectly fine.
 
-        Do not test nullable types with     Is Nothing    use    myInt.HasValue     instead.
 
-        Do not use Lambda expressions (there is no Lambda statements in VB9) so you cannot use the keyword “Function”.
 
-        Pay attention not to use relaxed delegates because this one is easy to miss in VS2008
 
-        Do not use Object Initializers
 
-        Do not use the “ternary If operator” … not the IIf method but this one     If(condition, truepart, falsepart).
 
As a side note, I talked about not using LinQ keyword nor the extension methods but, this doesn’t mean not to use LinQ in this scenario. LinQ is perfectly accessible from inside VS2005 if your client allows you to target framework 3.5. All you need to do is reference System.Core, use namespace System.Linq and use class “Enumerable” as a helper class… This is one of the many classes containing various methods that VS2008 sees as extensions. The trick is you can use them too! Simply remember that the first parameter of the method is the object you want to query on and then pass in the other parameters needed…
That’s pretty much all I see but I could have missed a few… If you know other things that are specific to the VS2008 compiler and which do not work under VS2005, feel free to leave a comment and I’ll modify my list accordingly (and notify our team here…) !
Happy coding all!

Saturday, April 17, 2010

Presenting LinQ to Objects in Ottawa


Here's the material for my introduction on LinQ to Objects at Ottawa's code camp... 

Happy downloading!

http://cid-bdf9cf467011e705.skydrive.live.com/self.aspx/.Public/Blog%20sample%20downloads/Ottawa%20Code%20Camp/Ottawa%20Code%20Camp.zip

 

 

Wednesday, April 07, 2010

Using the “Settings.settings” functionalities in VB.NET can be tricky…


 

Sometime you’re searching for something forever and when you find it, you realize it was right under your nose.  Maybe you were distracted by other things around… or maybe that thing right under your nose was so well hidden that it deserves a blog post…   That happened to me a few days ago while using the “Settings.settings” functionalities in my VB.NET application…  I thought it was a cool feature and I decided to use it… 

So there I am adding new settings with “USER” scope and StringCollection as the data type, testing my application and everything works perfectly fine...  That was before I decided to modify the “Value” of one of my settings…  After changing the value of one of my settings, I start my application again and, to my surprise, my new values aren’t showing!  Hmmm… That’s odd…  My setting was a pretty long list of strings so I was rather angry at myself for not saving my work after I was done…  So I open up the Settings.setting in the designer and click the ellipsis symbol to enter my string collection again, but to my great pleasure (and disbelief) my strings are there!!!  Alright, you rock VB.NET!  You’ve just save me a bunch of typing time and I’m thinking it’s just a simple Visual Studio glitch…  I hit “Save” then “Save All” (just in case) and finally I rebuild everything and fire up my app once again.  Huh?  Where are my darn strings????????  Ok there’s a bug there…  I open up the app.config and my new strings are there!!!  Alright, let’s recap…  My new strings are in the app.config, they show correctly in the Settings.settings designer UI but they aren’t showing at runtime…  Hmmmm?  Let’s try something else…  Let’s start the application but outside Visual Studio this time… I fire up the exe and BAM!  My strings where there!  I “alt-tab” and hit “F5” and BOOM, no strings!  So it’s a bug in the Visual Studio environment… or could it be a FEATURE?  I must admit that I’m a little confused over what’s a bug and what’s a feature in Visual Studio… lol!   Finally I found out there’s a “cache” for your Visual Studio located here: 

C:\Users\<your username>\AppData\Local\Microsoft\<your app name and a very weird temp ID>\<your app version>\user.config

When using the “Settings.settings” with a setting of scope “user”, this file is out of sync with your app.config until you manually decide to update it… The button is right there… under your nose… at the top left corner of your screen in the settings designer…  See the big “Synchronize” button there?  Yep…  Now that’s user friendly isn’t it?  Oh, and wait until you see what it does when you click it…  It prompts you and basically says:  “Would you like your settings to start working inside Visual Studio now that you found out that I exist?” and of course the right answer is yes… or rather “OK”…  Unfortunately, you have to do this every time you edit a value… On the other hand, adding and removing settings seem to work flawlessly without having to click this magical button… go figure!  Oh and I almost forgot… this great “feature” is only available for VB.NET…  A project in C# using Settings.settings will work perfectly EVEN when editing values…

Here’s a screenshot that shows this important button:

Button

Using other data types appears to work perfectly well…   Maybe it’s simply related to the StringCollection data type?  If you are a VB.NET programmer, you should pay attention to this when you plan on using the settings functionalities and your scope is “user” and your data type is StringCollection…

Happy coding all!

Monday, March 15, 2010

Steps to deploying on Windows Azure


Alright, these steps might be a little detailed and of few might not be necessary but still it's a pretty accurate road map to deploying on azure...

 This procedure assumes that you've created a solution with an Azure project into it.

 

1)     Open your solution

2)      Rebuild ALL

3)      Right click on your Azure project and click "Publish"

4)      It should open a windows explorer window with your package to be uploaded (.cspkg ) and its associated configuration (.cscfg) to be uploaded too.  Keep it open, you'll need that path later on...

5)      It should also open a browser asking you to login to your passport account, please do so.

6)      After this you will be redirected to the Azure Portal where you will see your Azure Project Name below the « Projet Name » section.  Click on it.

7)      Then you should be redirected to a detailed view of your account on Azure where you will create a new service by clicking the hyperlink on the top right corner.

8)      Choose the right service type for you, most likely the "Hosted Service" type

9)      Choose a « Label » name and click « next »

10)   Choose a name for your service and validate that the name is available in the cloud by clicking the "Check Availability" button

11)   At the bottom of this same page, you can choose to create a group for your service, use no group or join an existing group.  Creating a group means that all applications that belong to the same group will see no cost to exchanging data between other applications of the same group.  Most of the time when you create a single application, creating a group is not necessary.  You should choose a region that's close to your own region.

12)   On the next window, you should see a "Production" environment and a "Staging" environment.  Beware because "Staging" and "Production" are two different environments in the cloud and applications in "Staging" even when not runing do continue to rack in charges...  Choose an environment and click "Deploy".

13)   In the following window, browse to the path where your cspkg resides and then do the same thing with your cscfg file.  Choose a name for your Label,  and click "Deploy"...

14)   From now on, the clock is ticking and unless you have free Azure hours, your credit card is being billed…

15)   Click on the « Run » button to start your application

16)   Be patient.... be very patient…

17)   Once your application has finished starting, you should see a GREEN circle on the left side of the screen indicating that your application is READY.  Click the URL to test your application and remember that if your application is a service, you have to hit the "svc" class behind the link you see there.  Something in the likes of http://testvince2.cloudapp.net/service1.svc  (this is a fictional link)

18)   Hopefully your application will show up or in the case of a service, you will see your service's wsdl meaning that everything is working fine.

Happy cloud computing all!

 

 

Thursday, March 04, 2010

A few things I learned regarding Azure billing policies


 
 
An hour of small computing time: 0,12$ per hour
 
A Gig of storage in the cloud: 0,15$ per hour
 
1 Gig of relational database using Azure SQL: 9,99$  per month
 
A Visual Studio Professional with MSDN Premium account: 2500$ per year
 
Winning an MSDN Professional account that comes preloaded with 750 free hours of Azure per month:  PRICELESS !!!   
 
But was it really free???? Hmmm… Let’s see.....
 
Here's a few things I learned regarding Azure billing policies when I attended a promotional training at Microsoft last week...
 
 
 
1)  An instance deployed in the cloud really means whatever you upload in there... it doesn't matter if it's in STAGING OR PRODUCTION!!!!   Your MSDN account comes with 750 free hours of small computing time per month which should be enough hours per month for one instance of one application deployed in the cloud...  So we're cool, the application you run in the cloud doesn't cost you a penny....  BUT the one that's in staging is still consuming time!!!   So if you don’t want to end up having to pay 42$ at the end of the month on your credit card like this happened to a friend of mine, DELETE them staging applications once you’ve put them in production! This also applies to the instance count you can modify in the configuration file… So stop and think before you decide you want to spawn 50 of those hello world apps  .
 
 
2) If you have an MSDN account, then you have the promotional 750 hours of Azure credits per month and can use the Azure credits to explore the Cloud! But be aware, this promotion ends in 8 months (maybe more like 7 now) and then you will most likely go back to the standard 250 hours of Azure credits. If you do not delete your applications by then, you’ll get billed for the extra hours, believe me…   There is a switch that you can toggle and which will STOP your automatic enrollment after the promotion and prevent you from renewing the Azure Account automatically. Yes the default setting is to automatically renew your account and remember, you entered your credit card information in the registration process so, yes, you WILL be billed…  Go disable that ASAP    Log into your account, go to “Windows Azure Platform” then click the “Subscriptions” tab and on the right side, you’ll see a drop down with different “Actions” into it… Choose “Opt out of auto renew” and, NOW you’re safe…
 
Still, this is a great offer by Microsoft and I think everyone that has a chance should play a bit with Azure to get to know this technology a bit more...
 
 
Happy Cloud Computing All

Tuesday, February 02, 2010

Windows® API Code Pack for Microsoft® .NET Framework - Use at will !


 

Today I went to a presentation made by Kate Gregory, Regional Director, Toronto
on this free API from Microsoft and once again, I must say wow...  I say again because I had already seen a similar presentation made by Éric Moreau a few months ago but back then I wasn't running Windows 7 and had other things in the pipeline...  Today I'm running Windows 7 and I can't wait to see this API in action.  Most of the features are one liners so they are easy to take advantage of and they really give our applications a sexier look and an enhanced user experience!

I truely recommend that you take a look at it just so you know the next few applications you build can benefit from this great tool.

Use at will !

 

 

Tuesday, January 19, 2010

Coding Dojo at .NET Montreal Community


Yesterday I gave a conference on LinQ to Objects at the .NET Montreal Community.  The format was not your typical conference, it was a coding dojo!

Everything went well and I think many people enjoyed to event.   I'm posting a link to the solution that contains all the exercices the group did with the the answers included.  Unfortunatly, it's in french :)  If someone would like to have the exercices in english, about 20 of them, please post a reply and I'll put the english version here ASAP...

 

Have fun!

 

cid-bdf9cf467011e705.skydrive.live.com/self.aspx/.Public/Blog%20sample%20downloads/Conf%c3%a9rence%2018%20Janvier%202010%20GUVSM/CodingDojo-LinQ.zip

 

 

Monday, December 07, 2009

Behold, the "swiss knife" of delegates... Action T !!!


 
When writing multi tier systems, a common thing that architects or any other person in charge of communications between tiers will do is define the public interfaces for the system. Another thing we often do when designing such systems is define delegates available for use within the code. This is something I always thought was important to do but, honestly, how much time do I end up losing writing a new delegate declaration each time I need one? Way too much in my opinion! Since framework 2.0 and the arrival of Generics, we had the opportunity to start using the Action<T> delegate. This generic delegate works like an all purpose delegate and I call it the “swiss knife” of delegates. 
Basically any method that takes one parameter and returns “void” can be used as the target of this signature! What, you expected Microsoft would create a delegate for each type available in the framework??? Nah think “Generics”!!! Simply specify the type of the parameter when declaring the delegate, like in the following example when I use a method that takes a string as the only parameter:
public Action<string> myDelegate;
Also, if the method you want to use as the target of the delegate as no parameter and returns void, you can use the Action class available from within the “System” namespace.
With framework 3.5, things have evolved and our “swiss knife” has added some extra tools for us to use! The Action<T> delegate has now 3 new flavors namely Action<T1, T2>, Action<T1, T2, T3> and Action<T1, T2, T3, T4>. Now you can use this fantastic time saver on methods that have up to four parameters! Look at the following:
public Action<string, int, double, Employee> myDelegate;
In framework 4.0, they literally transformed our “swiss knife” into an über “swiss knife”!!! This one goes out to the brave men and women from the .NET Framework who have decided to add 12 more flavors of Action<T> delegates bringing the total Action flavors to 16… That’s awesome… more goodies for us to use but, why 16?  I think that’s a lot but still, a great asset.
Alright, now what should you use if the method you want to use with a delegate returns a value? Hmmm… Action<T> clearly states that the target has to return void. The answer is Func<TResult>!!! Using the same pattern, the designers of the 4.0 .Net Framework added 16 flavors of a method that returns a value. The only difference between the two delegates is that Func wasn’t available in the 2.0 .Net Framework…
 
Predicates are going to be for the next time…. Until then, happy learning!

Sunday, November 15, 2009

Cross-thread operation and UI tips


 
Sometimes you hook yourself to events in the system that you are building which you know will be fired from another thread than the thread that will handle or consume the event. A good example of that would be to hook yourself to a System.Timers.Timer.Elapsed event from within a windows form.  In the event handler you need to update some visual controls.... Damn it!  You receive an “InvalidOperationException” saying “Cross-Thread operation not valid...” !!!  How do you solve that again?  Oh yeah that’s right, in the exception viewer, click the “How to make cross-thread to windows form controls”... After 20 minutes of reading you’ll implement the solution and say “man that is one useless method I just created and I need to create ten or twenty more methods identical to this one just to update my darn UI !”.  I call this "code spam” !
The problem is easy to understand...  You need to run the code that wants to play with UI controls from the same thread as the UI thread by calling “this.Invoke” and passing in a delegate that points to a method which will update the UI...  Now that’s exactly what you did previously... and it sucked because you polluted your code with a useless method an potentially many of those.... No need to say that there are another ways of doing this.  Why not simply use the handler itself as the target of the invocation?  You’re already inside the right method, aren’t you???  It simply wasn’t invoked from the right thread... Look at this code which handles a System.Timers.Timer.Elapsed event and then successfully updates the UI.
 
The magic occurs at line 31 where I test whether or not the current executing code runs from the same thread as the window or “Form” containing the visual controls. If it’s not, then an “invoke” from the “Form” is required. This part is the “True” part of the “If”. In there I call the method I’m already in (call it recursion if you want) using a delegate that should match most if not all events in the .NET Framework being EventHandler<TEventArgs>. This is a generic signature that specifies a method that accepts a first parameter of type “object” and a second parameter that must inherit from “EventArgs”. Look at the following to better understand this delegate:
 
As soon as line 33 executes, the code will jump to line 27 and re-enter the event handler a second time. Then it will hit the magic spot once again but this time, the code has been fired from the same thread as the UI!  Remember the “this.Invoke”?  Then it will go to the “False” part of the handler and will update my UI without a problem.  Then if you continue to trace, the second call to “timer_Elapsed” will end and the original call to the “timer_Elapsed” handler will continue on line 35. Now, how cool is that?  I find it quite neat and easy to understand.
There is one more variant of this technique I’d like to show you and which will lead me to introduce the subject of my next entry (sometimes next week) and it uses the “Action” generic delegate.  Even tho I personnaly prefer using "EventHandler<TEventArgs>" when I'm inside an handler, and "Action" when I'm not, nothing forces you to.  There's got to be a generic signature for the “Action” delegate that matches your method and if not then you can always refactor it so it fits one of the five generic “Action” flavours offered with framework 3.5. Look at this code for an example.

Alright so that's it for now and if you want to learn more about 2 interesting delegates being "Action" and "Predicate" stay tuned and give me a week to work on that .

Here's the code if you want to take a look at it and happy Multi-Threading all.

Wednesday, October 28, 2009

Less plumbing and more productivity thanks to nVentive and their Umbrella project!


Who here uses IDictionary classes in their projects? Raise your hand. Keep your hand up if you cannot bear the sight of having to call another ContainsKey method. Keep it up if you cry at the idea of having to use the “out” keyword in conjunction with the TryGetValue method... Keep the hand up if you consider that removing items should be allowed from inside a foreach loop. Is your hand still up? Yeah, mine too .  Alright let’s all take a break. This is just one of the numerous annoying little things that all of us still have to do on a daily basis instead of focusing on business needs and real functionalities in our programs. After more than 8 years, one would have thought the many programmers behind our beloved framework would have acted and fixed those annoyances already. Guess again, I’m afraid we’re still in for many years of plumbing... Unless comes Umbrella!
It took the ingenuity of a few persons from nVentive, a Montreal based company, to fix those holes in the framework and polish some of those rough corners. Well they didn’t really fix the framework itself, but they provided us with a non intrusive set of extension methods to use everywhere in our code. This thing is awesome... Did I mention it’s non intrusive? Oh sorry. Then did I mention its open source? Ah Ah!!! I knew I had forgotten something important. Another thing worth mentioning is since this set of tools is based on extension methods, you can call the extension methods on null objects... That’s very practical for your defensive programming validations. One more thing about extension methods is that you can also chain your calls! Here are a few examples to show you just how many useful things this set of extension methods can do for you. Some of these examples are extension methods we often build for our projects but this time they’ve pushed the concept to the extreme and rendered them generically usable in all projects and applicable to all business domains.
 
1)      Here’s the extension to remove items from a collection based on a condition
Remove<T>(this ICollection<T> collection, Func<T, bool> predicate)
...and this is how to use it with a Lambda so there is no need to loop backward in the collection or loop once to put items to remove in a secondary list and then loop a second time to remove the items contained in the second list from the first list:
List<int> listOfIntegers = new List<int> { 1, 2, 9, 9, 9, 9, 8 };
 
listOfIntegers.Remove(item => item == 9);
 
2)      Have you ever wondered why the .NET framework had a ForEach method on List<T> instead of an extension on IEnumerable<T>?  Umbrella to the rescue...
 
IEnumerable<T> ForEach<T>(this IEnumerable<T> items, Action<T> action)
 
Now anything that’s enumerable will have the ForEach extension method available
 
 
3)      There’s the extension to get a value from an IDictionary without having to write a few lines of code all the time.   If it cannot find the desired key, it will automatically add an object from the factory you supplied as a parameter to the dictionary and set the dictionary entry key to the searched key passed as the first parameter.
 
TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
 
This is how to use the method:
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(0, "hello 0");
dictionary.Add(1, "hello 1");
dictionary.Add(2, "hello 2");
dictionary.Add(3, "hello 3");
dictionary.Add(4, "hello 4");
string found = dictionary.FindOrCreate(10, GenerateNextStringFactory);
 
4)      Do you know what Code Contracts are? I know you can download it for 3.5 and VS2008 and that it comes standard with VS2010 and .NET 4.0, but let’s say we don’t know. Tired of that “2 liner” you use all the time while doing your defensive programming when testing all your method parameters for null values? And what about those string parameters where you have to do a bunch of “if” to know whether the value was null or empty? Here’s the solution, have each variable call the following which will throw the ArgumentNullException:
 
methodVariable.Validation().NotNull("methodVariable")
 
I wonder if they could not have made it even easier for us and reflected the parameter name instead of forcing us to pass it as an argument?
  
 
 
5)      If you want to dive into serialisation and don’t want to mess with Formatters and Streams then Umbrella is for you.   Here’s an example of how simple it is to serialize stuff with these extensions. Also, a few weeks ago I blogged about custom serialization and gave you my personal helper class to help you serialize stuff. I also said there was no way to create extension methods based on [Serializable] attribute... I still believe it’s the case but when I saw Umbrella’s implementation using extension methods, I wondered, why simply try to serialize classes that are tagged as serializable? Now I see there’s nothing wrong in having every possible class in the framework being able to serialize itself. Worst case scenario, you get an exception when you call the method on something that’s not tagged as [Serializable]. Isn’t that exactly the desired behaviour?    There’s the code...
variableName.Serialization().Xml("c:\\myclass");
All these goodies come from a single namespace. So all you have to do in your code is add a reference to the Umbrella DLL (or add the project straight to your solution, remember it's open source) and add the following namespace to your code:
nVentive.Umbrella.Extensions
If you download the code and check out how it’s made, you’ll learn a great deal and won’t get lost in exploring the solution. They’ve put everything in the same namespace for us, the programmers, so we don’t have to bother searching for the right namespace to use but they didn’t put all the code at the root of their solution. Everything is well organized even if the directory structure doesn’t match the namespace. Just remember it’s intentional and better that way.
I hope I gave you enough information to have you download the code and explore it inside your current projects.  I’m just starting to play with this set of tool but from what I can see there’s great benefits in having your programmers code more of your business needs and less of the traditional plumbing. I would also suggest reading a little bit on Extension Points therefore I’m referring you to a post from Éric De Carufel, one of the contributors on the Umbrella Project in CodePlex.
Happy coding and exploring!

Monday, October 19, 2009

My thoughts on Try – Catch – Throw


One of the most common question people ask me in the teams I’m in is the following: Where should I put Try – Catch blocks? The second most popular is equally challenging: What is the best method to re-throw an exception? This post will try to answer both questions. Before I start with this topic, I must warn you that the following is not the official “best practices” but rather my own personal opinion on the subject, based on my past experience.  I think that Try – Catch blocks are a great asset of our programming language but they also tend to be the Achilles’ heel of our programs.  I say this because it’s not a good idea to write software that you'll have difficulties debugging effectively. It's often the case when people publish stack trace informations with eroneous line numbers in them.  What good is a stack trace when you end up on a "throw" instruction when trying to reproduce the bug in your developement environement?  That means make sure your exception’s “stack traces” have the right line numbers when you publish them because you only have one "try" at finding the cause of an error with stack traces...  This article assumes you’ve deployed your PDBs and that you are in a secured environment, but PDB issues are for another post... Let's get dive into this!

   

I will start this post by answering the second question mentioned above.  After catching an exception in your program, you decide to re-throw the exception back up the call stack.  You can do that with one of the following techniques:

A)     The “Throw” keyword alone.

B)      The “Throw” keyword followed by the variable name used to catch it (typically “ex”).

C)      Throwing a new exception (typed if possible) and adding the catched exception as the inner exception of the exception you’re about to throw.

So, which one of these techniques should we use to re-throw an exception?  Should we use any of those techniques?  Are they all the same and do they all yield the same results in the end?  Well, let’s give it a try J

Here’s a solution that you can download and try every combination yourselves.  In the mean time, here are the results:

 

Using technique B is the worst practice of all 3.  It will inevitably break your stack trace and replace your original exception’s line number with the line number at which the exception was re-thrown.  This renders your stack trace almost useless.  Good luck in your debug sessions...  See the following stack trace screenshot which should show an error at line 119 but we’re seeing line number 109 instead.

 

Using the A technique can be as damageable as the B technique even though we see this technique of simply using the “throw” keyword almost everywhere...   Look at this stack trace which displays line number 175 when in reality it should be displaying line number 168.  How shocking!

 

The only technique that allows re-throwing an exception and that keeps the stack trace’s line numbers intact is C.  Look at this stack trace and you'll see the correct line number is shown which is 257.  But throwing a new exception has a cost on performance.  In fact, I do not consider this to be a decisive factor but, yes, creating another exception is time consuming.  Then again, it’s time consuming on and “exceptional” basis...  So once in a while, your program will be slower to tell you to contact your administrator because something went wrong...  So what?  Remember that your program should do something other than generate exceptions all the time and if it’s not, then you’re already in trouble.  I’m sure your client isn’t paying you to build an exception generator.

Of course the default “bubble up” is always the best option but sometimes, you have to catch possible exceptions.  This exception was bubbled up and gives us the right line number being 206.  My advice to you is this: be very precise in which exception you need to catch when this situation arises.  No need to catch more than you should, let other unplanned exception bubble up and re-throw the exception you wanted to catch as the inner exception in a new exception.  Hopefully these screen shots were enough to have you download the solution above and try these different try – catch combos.

Now that you know a little bit more about the side effects of re-throwing an exception using something else than throwing a new exception, let’s see where we should use try – catch blocks.  Ever heard of “stack starters”?  Of course you didn’t since this is my very own term for “event handlers”, what was I thinking.  Event handlers are THE most important thing to secure when speaking of error handling.  In my book, each and every “event handler” has to be protected by a “try – catch – all” exception block.  That means a try – catch block catching “Exception” as its type.  Of course you can always rely on good ol’ global handlers to publish all your exceptions.  Please do so!!!  But use global handlers as safety nets...  Why?  Because YOU are responsible for securing your code from unhandled exceptions.  Remember that when writing code inside an event in your program, you’re simply coding inside an area where another programmer momentarily passed you control over the execution of HIS code.  Welcome to the bottom of the programming food chain, where I unfortunately reside too...  Here’s an example of what can happen if you don’t systematically catch all exception in the events you consume.  Click here for a screen shot of the code I want to show you or fire up your favourite disassembler program (mine being Reflector) and browse to the System.Windows.Forms namespace to find the DataGrid.  Open the DataGrid and disassemble the OnPaint method.  In there you will be able to see that the programmer who wrote this piece of code has guarded against anything that could happen in his code....  Good thing!  Every programmer should keep his shelves tidy and clean up the mess in his state variables when something goes wrong in his code.  Let’s dig a little deeper.  Locate this line in the code:   base.OnPaint(pe);.   Disassemble it too...  There you will see the base class of the DataGrid actually calls the event handler you added when you consumed the OnPaint event in your code.  But what happens to the gentlemen’s code if YOU forgot to catch all exceptions in your code when you consumed the OnPaint event?  Yep, he’s going to catch it for you....  Great you think?  Not really...  You made him think HIS code threw the exception and look at all the code he’s going to run to clean up what he thinks is his mess...  You're lucky, there wasn't a MessageBox.Show() in there displaying a debug message in cantonese!  Ok you need to set aside the fact that in this case, he’s detecting whether or not he should simply re-throw the exception or do his stuff with this line of code so, I’m busted ...  It’s hard to find a real code example that matches what I want to demonstrate.  You need to keep in mind though that when using controls this scenario could always happen.  Hopefully this example convinced you to secure your “stack starters” with a “try – catch – all” block.

Sometimes catching exceptions in your business layer or your data layer is inevitable but, you should always consider re-throwing the exception to signal the initial caller that something went wrong at one point in the chain.  When I need to stop the execution of an action in my program, I always choose exceptions over Boolean returns for my methods.  To me, exceptions are far easier to handle than having to take care of returning a Boolean in each method I call and having to deal with coding the return chain for every method.  Most of the time, when an exception happens in my business layer, its serious enough for me to break whatever I was doing and signal the error back up.   Rarely have I seen “something unexpected happening” in my business or data layer which would not influence the outcome of the initial call.

Another thing worth mentioning is be aware of not hiding exceptions.  Using the following pattern is something you should try to use only if necessary as it renders debugging a real nightmare.
In french I call this pattern “Try – Cache” which could translate to "Try-Hide" and means try to hide the exception...  Anyone remembers the good ol’ days of “On Error Resume Next” in VB?  What a smart way to bullet proof your application against that pesky message from Windows (huh... NO... it’s not).

I hope you see things differently or at least from another eye now and that this blog post was interesting even though it was long.  Happy code reviewing!

Sunday, October 11, 2009

How ISerializable are you?


Serialization is a beautiful thing. Now that was a geeky comment.... Jokes aside, it is. Standard .NET serialization is quite simple. Tag your class with the [Serializable()] attribute, make sure all your state variables are serializable and voila. But what if some of these variables aren’t serializable? Then you simply need to tag those variables as [NonSerializable()] and then you are really done. Of course I could get into the details of all this but this post isn’t about standard .NET serialization.
Custom serialization on the other hand is a little bit trickier. Not only do you have to go through all the same process as standard .NET serialization but,  since your class or a class in your class hierarchy implemented ISerializable, now you got to do even more stuff just to get your states to travel from point A to point B....  So here’s the procedure to get it to work:
1)      Do you have states (variables) in your class? If not, then go to step 4 and you’re almost done... Lucky you! Each class in the class hierarchy is responsible for managing its states and you should not take care of the state variables of your base classes. Mind your own business :)

 
2)      Override GetObjectData and call the base method inside there... I personally prefer calling it on entering the method.
 
 
3)      Inside the GetObjectData method, you need to “store” the states that you want to transfer from point A to point B. You do this by adding entries to the variable named “info”. This variable is passed to GetObjectData by the CLR. Parameter “info” is of type “SerializationInfo” and resembles a “NameValueCollection” in its usage. Simply call “info.AddValue” with the overload of your choice to add each state variable of the class you want to serialize and it will be added to the serialization process. You can imagine this operation was like telling the CLR which states of your class needed to be serialized. Your code should look like the following:
 
public override void GetObjectData(SerializationInfo info, StreamingContext context)
                       {
                             base.GetObjectData(info, context);
 
                             info.AddValue("currentUser", this.currentUser);
                             info.AddValue("runningAs", this.runningAs);
     }
 
 
4)      Now that the CLR knows what to serialize, it needs to know what to do on the other end of the process, once it reaches point B...   We have to tell him how to reconstruct your class’s states. Remember it’s not the class itself that was sent on the wire, it was only its states. On the other side of the wire, the CLR will create a NEW class of the same type as yours and you need to tell him which states goes to which variable. In .NET we do not inherit constructors from our base classes, we need to redefine them. In our case, one very important constructor needs to be redefined and also needs to call his matching constructor (chaining) in the base class. Its signature is the following:
 
protected MyClass(SerializationInfo info, StreamingContext context) : base(info, context)
You should definitely keep the “protected” modifier in place. Why? Well, because this constructor is not meant to be called by you except when you call it from a base class. This constructor is reserved for the CLR to use and only it has all the information needed to inject the right thing at the right place once we’re at point B.
5)      Once the constructor redefined and its matching base class constructor called, take a closer look at the first parameter of the constructor...   The CLR will inject the “info” variable into the constructor. This variable contains all the states you and your base classes added to it a few moments earlier on the original instance when the CLR called GetObjectData prior to serializing the class at point A. Then you can simply transfer each value from the “info” variable back to the state variable that holds it in the new instance of the class.  It should look something like this:
 
protected MyClass(SerializationInfo info, StreamingContext context) : base(info, context)
{
                          this.currentUser = info.GetString("currentUser");
        this.runningAs = info.GetString("runningAs");
}
 
6)      This step is the most important step of all. Test your serialization!!!! I’ve build a nice little helper class for this and I’ll give it to you all so that you have no more excuses not to test your serialization prior to going live. Those of you who know me are already thinking “whaaaat? Normally this guy hates helper classes so why not use an extension method instead?”. Alright but to extend which type? ISerializable? Sure, then you can use it on some classes but not all classes because you cannot define an extension method based on metadata like the [Serializable()] attribute. It would have been nice tho J. So use the helper to serialize and deserialize a class instance and compare ALL states one by one. This is best done in a unit test by the way. You would be sure to test all your class serializations in every build of your product. In the helper, call “TestObjectSerialisation” and catch the returned object. This method serializes the instance of the class you give it and then deserializes it in memory prior to returning it to you, ready to be compared to the original instance. 
  
I hope this post helped you understand the basics of how implementing ISerializable works and what needs to be done when you do so. For your information, one very common place where you need to do this is when you create your custom exceptions.  The type "Exception" implements ISerializable...  Happy coding !
 
 

 

Copyright © Vincent Grondin