Wednesday, December 19, 2012

DotNetDude joins Synergy Systems

I'm pleased to announce that DotNetDude Development and Synergy Systems have joined forces with big plans for 2013.

Synergy Systems has established itself as a leader in recruiting by focusing on the most sought-after talent with a critical eye towards both technical and soft skills. The folks at Synergy pride themselves in establishing relationships with the upper echelon of IT talent as well as the most desirable companies.

DotNetDude Development has invested heavily in the IT community and Synergy Systems is helping to continue this push in the new year by sponsoring appearances at technical conferences. Be on the lookout for me at CodeMash in January!

Thursday, November 22, 2012

Microsoft Fakes Bait and Switch?

Is it possible Microsoft tricked developers into adopting their code isolation framework in an attempt to force upgrades to the Ultimate version of Visual Studio 2012?

When I first learned about the Moles framework from Microsoft Research, I was excited at the possibilities for unit testing and began presenting it at user groups and conferences. I was even more excited after Microsoft announced that a new version of this framework, named Fakes, would be included with Visual Studio 11 (now 2012).

Microsoft's documentation originally indicated that Fakes would be included with both Premium and Ultimate, but early adopters noticed the VS2012 Premium release candidate did not include Fakes and the documentation was later updated to indicate it would only ship with Ultimate.

Meanwhile, Moles is no longer supported in VS2012. So where does this leave those who adopted Moles and use the Premium version of Visual Studio? It appears they will be forced to upgrade to Ultimate or abandon the use of Microsoft's code isolation framework.

I choose to give Microsoft the benefit of the doubt. I'm sure the original intention was to ship Fakes with the same versions as were previously compatible with Moles. Discontinuing Moles made sense when a new-and-improved framework was slated to take it's place. The decision to restrict the use of Fakes to Ultimate was surely made without considering the ramifications to their existing customers.

The question remains of what, if anything, Microsoft will do to address the needs of those customers that have been left out in the cold.

Tuesday, October 23, 2012

Three Tips for Recruiters

The longer I work in the software development community, the more recognition I get from recruiters as someone who can help them find candidates and the more colleagues that approach me asking for career advice. I love helping good people on both sides of the equation, but there are a few things I expect from recruiters.

Be Candid

When I speak with a recruiter who is unwilling to share information about the client for fear they will be circumvented or will not provide a general range for the salary/rate, it says to me that they do not trust their own value and consider the candidate an adversary.

Experienced recruiters bring more to the table than a job description. They, or someone they work with, have a relationship with the client company and a reputation of bringing them solid candidates. A resume presented by such a recruiter may be given more credibility and often goes to the top of the interview list.

In my experience, providing a general range of possible compensation for a position is a win-win. It gives a potential candidate the information they need to decide if the opportunity is worth pursuing and keeps from wasting anyone's time.

Avoid Random Referral Solicitation

I can't count how many times some random recruiter has asked me to help them expand their network by recommending them to my colleagues or, even worse, asked for me to give them contact information for possible candidates. There is a short list of recruiters which I provide when someone I know is looking for a gig and these are people who I've known for years and have a solid reputation for taking care of their candidates. It baffles me that someone would expect me to recommend them when I cannot vouch for their character and abilities.

That said, I encourage recruiters to email me job openings that fit my niche as I may come across someone who would be a good fit. While I appreciate having these on hand in case a colleague expresses a need, I do not actively seek candidates for these positions unless there is significant motivation for me to do so. Motivation comes in many forms, but the most straightforward is a referral fee. If a recruiter who I do not have a relationship with expects someone else to spend time and energy helping them fill a position, they should expect to offer compensation in the same way that I would share part of my billable rate should I need help from another software developer who is not getting paid for the work.

Get Involved

Having served as Treasurer, Vice President, President and now Board Member for the Nashville .NET User Group, I often encourage others to drop by and find a way to participate in the community. It can be an important tool for software developers, but is absolutely vital for a recruiter.

Imagine taking all the juiciest most healthy fish in a lake and putting them in a swimming pool. Wouldn't that be a great opportunity for a fisherman to make a great catch? User group meetings are where the best and brightest gather and recruiters are welcome at most of them, so long as they respect the meeting and are not overbearing. Even if the recruiter doesn't speak to anyone about opportunities during the meeting, they have a connection to reference next time they call.

Attending community events is not just about networking. The bulk of a technical presentation might be over a recruiter's head, but over time they can pick up meaning behind the buzz words and witness individual and group reactions. Understanding these reactions can help identify the right candidates for a position and what motivations particular candidates might respond to.

There's a wealth of non-technical education that takes place as well. By watching how people interact one can learn quickly who people in the community respect and how they interact. Seeing how someone interacts with their peers can be a great indicator for how they might fit into a team.

Chances are, any recruiters who are taking the time to read this article are already on the right path. Hopefully these tips will help provide direction to someone I will, one day, have the pleasure of working with.

If you have any additional tips or thoughts on this topic, please feel free to leave a comment below.

Monday, October 8, 2012

Bank of America's $888,888.88 Surprise

If you have a Bank of America checking account, you could find yourself nearly a million dollars in debt as a result of depositing a check that bounces.

I've been a Bank of America customer since 1998 and have never had a problem with my checking account until last week when I noticed an $888,888.88 withdrawal appear. As a software developer, my first thought was some sort of system error so I searched the internet to see how many other people had experienced similar glitches, but I seemed to be the only one. Then I started to worry that it was fraud so I contacted customer support. They transferred me to Sheldon Walker in the Global Fraud Prevention department where I was informed that they had applied this charge to prevent me from using my account. Their justification was that a check from my renter had bounced leaving insufficient funds, so to ensure that the bounced check was re-payed they deducted nearly a million dollars from my checking account. Sheldon gave me his direct number (626-397-6029) and told me he would have to be contacted to remove the hold once my account had sufficient funds to cover the bounced check.

I knew my client's next invoice was being processed Thursday night so I waited until the funds were deposited and called Sheldon first thing Friday morning. I left a voice mail message that the funds had been added and I needed the fake charge removed. With the weekend fast approaching I called back every hour leaving a new message, but Sheldon never returned my call. 

I've never heard of a bank purposefully creating fake withdrawals of arbitrary amounts and can't fathom why they didn't place a hold for the amount of the bounced check. It all seems quite unprofessional and makes me think I need to find a bank that will take better care of their account holders.

Apparently I'm not alone. Here are others who have gone through the same nightmare including a TV news story:


UPDATE 10/09/2012:
I received an email notification this morning that my Savings account balance had dropped to $0. When I logged into online banking I found that Bank of America had drained my savings account as "OVERDRAFT TRANSFER HOLD". I tried one last time to reach Sheldon Walker, the employee to whom I first spoke with regarding the hold, but my call went to voicemail so I decided to try another route.

I then called BoA Risk Management (877-240-6886 option 2) and was transferred to someone who was able to remove the -$888,888.88 entry. They were very apologetic and, after a few minutes on hold, informed me that they had removed the extra fees that had been added as a result of the hold. I can verify that my account now shows no trace of the $888k entry and I'm back to black. The savings transfer hold and overdraft fees still show up, but I'll give those a while to clear before calling back.

FINAL THOUGHTS:
I'm happy to have my account back, however this whole experience has shaken any faith I had in Bank of America as a safe place for my money. Because one deposited check bounced, I lost access to my account for nearly a week and watched my savings siphoned off into a black hole of fake transactions. If not for my own persistence, this would have surely gone on much longer as nobody from Bank of America ever initiated contact with me. I had to investigate the cause for the mysterious charge and hunt down someone who could rectify the situation. There's no excuse for a bank hanging a customer out to dry like that with no indication of the cause or what needs to be done.

Time after time, Bank of America makes it clear that the customer is NOT their priority so I'll be moving my personal checking, savings, and business accounts as soon as I can decide on a new home for my money.

Friday, September 28, 2012

Conference Survival Guide

The fine folks running Bar Camp Nashville asked me to write a short guide to help attendees get the most out of their un-conference experience.

General Tips
  • Plan Your Schedule - Note which sessions you want to attend in advance. Choose backup sessions in case your first choice gets rescheduled or canceled.
  • Dress Comfortably - It's hard to concentrate on the speaker if your feet are hurting.
  • Bring a Bag - The conference might provide one, but then it's going to look just like everyone else's and you run the risk of losing it.
  • Take Breaks - All those sessions can get overwhelming. Don't be afraid to take a break to digest and discuss what you've heard with others.
  • Don't Be a Loner - Meals are great networking opportunities and you can usually find at least one other person who is hungry and would enjoy the company.
  • Be a Loner - Don't spend the whole conference around the same people, especially coworkers or friends who you see regularly. By striking out on your own you may meet people you otherwise wouldn't.
  • Eat Left Handed - There's no telling what kind of germs you've accumulated by shaking hands, not to mention all the door knobs and railings. Wash your hands regularly, use sanitizer and try not to touch your face or handle food with your dominant hand.
  • Use Twitter - Even if you never post a single tweet, Twitter is a great way to find out what's going on and connect with people. Search for the conference name, hash tag or influencers to see what people are up to.
  • Write on Business Cards - When handing out or receiving a business card, flip it over and write a short note on the back to help later with recalling what was being discussed.
  • Follow Up with Contacts - Don't just throw all those business cards in a drawer when you get home. Take a moment to write follow-up emails and enter their contact information into your address book.
Session Tips
  • Taking Notes - Write down reminders for yourself when you hear/see something you want to look at more closely later. Ask if the presenter will be posting their slides. If not, use your phone's camera to take snapshots of important slides. If so, then there's no need to copy them down and you can focus on what the presenter is saying.
  • Ask Questions - Unless the presenter has asked to hold questions until then end, don't be afraid to speak up. Chances are, someone else in that room has the same question and is afraid to ask.
  • Use the Two Foot Rule - If you're not getting something out of the presentation, don't be afraid to use your two feet and walk out to try another session or just socialize.
  • Following Up - Most presenters will share their email address or twitter handle as a way of contacting them with questions. Take advantage of their offer to start a dialog.
  • Do Something - Find a way to use what you've learned in the session. Teaching it to others is a great way to be sure you understand and will retain your new-found knowledge.

Monday, September 24, 2012

Memphis .NET User Group (MNUG)

Last week I mentioned that I'll be speaking at the NE Arkansas .NET User Group on the 27th. Since then, we've arranged for that presentation to be broadcast via Live Meeting and the Memphis .NET User Group will be joining us live. Someone local will monitor the meeting chat room and relay any questions or comments from the online participants.

UPDATE:
If you attended this talk and would like to provide feedback, you can do so at SpeakerRate.com.

Thursday, September 20, 2012

New Talk - Going Solo

I'm working on a new talk for Bar Camp Nashville and have never had so much fun putting together a presentation. The title of my talk is, "Going Solo - How to Train Your Wookiee" and am going with a Star Wars theme. Here's what I've got so far:

Description: When you started you were but the learner, now you are the master. You can make the Kessel Run in less than twelve parsecs, but you're getting tired of Greedo and Jabba demanding a cut. If you dream of being your own man, join us in discussing how to choose and outfit your ship to embark on the quest for freedom.

Topics:
  • Opening Introduction - "I'm Gaines Kergosien, I'm here to rescue you."
  • Getting Rich - “Wealth...more than you can imagine.”, “I don’t know. I can imagine quite a bit.”
  • Possible Pitfalls - "I've got a bad feeling about this."
  • You Can Do It - "I find your lack of faith disturbing."
  • Marketing Yourself - "The Force is strong with this one."
  • Creating a Company - "Aren't you a little short for a stormtrooper?"
  • Contractor Agreements - "Let’s just say we’d like to avoid any imperial entanglements."
  • Managing Finances - "Into the garbage chute, flyboy!"
  • Paying Taxes - "The Phantom Menace"
  • Tax Deductions - "These aren't the taxes you're looking for."
  • Working Remotely - "You're all clear, kid! Now lets blow this thing and go home!"
  • Subcontractors - "Help me Obi-Wan Kenobi. You’re my only hope."

Special thanks to Scott Walters and Philip Wilson for helping brainstorm ideas for the talk.

UPDATE:
The schedule has been finalized and we'll be in the Cadillac Ranch Poker room at 3:45pm on October 20th.

UPDATE 2:
Here's a quick preview of a few title slides from the presentation:

UPDATE 3:
We'll be streaming live at http://www.livestream.com/barcampnashville5

Tuesday, September 18, 2012

.NET Testing Frameworks

Most of my testing experience has been with MSTest, NUnit and Selenium and I feel this is an area I need to explore in more depth, so I thought I'd put the question to my colleagues and readers: What testing frameworks do you prefer and why? Below are a few lists of some .NET oriented frameworks with some notes on what sets each of them apart from others. I welcome comments confirming, challenging or correcting these notes as well as suggestions of others I may have missed.

Unit Testing
  • MSUnit - Included with VS, Easy to implement
  • NUnit - Most common third party framework
  • xUnit - Extensible, lends itself to TDD/BDD
  • MbUnit - RowTest for parameterized testing

Acceptance Testing (web)
  • Selenium - Relies on CSS ID and class selectors
  • WatiN - Works best with IE

Tools

Mocking

Monday, September 17, 2012

NE Arkansas .NET User Group

I'm scheduled to speak at the Northeast Arkansas .NET User Group on September 27, 2012. The topic of this talk will be Testing the Untestable with Microsoft Visual Studio 2012 Fakes. I've given this same talk several times at regional conferences and user groups and an overview can be found on my blog, however one great thing about speaking at local groups like this is that the audience helps direct the session and we often end up focusing on areas that are most useful to that particular group.

While anyone is welcome to show up, the group leader has requested that attendees RSVP so they have an idea of how many to expect. See you there!

UPDATE:
If you attended this talk and would like to provide feedback, you can do so at SpeakerRate.com.

Tuesday, September 11, 2012

Great MVVM, WPF, SOA and EF4 Articles

I was asked to put together some links to articles that would help our IT department ramp up on some of the patterns and technologies we're using. By the time I was done with the email, I realized it might be of use to others outside our organization so part three of my MVVM with WPF series was born. There are many approaches and I highly recommend researching beyond this handful of articles, but for anyone not yet familiar with these concepts I hope they help.



The Model-View-ViewModel (MVVM) pattern helps to cleanly separate the business and presentation logic of an application from its user interface (UI). This separation is key for testability, maintenance and scalability.

Here’s an introduction to MVVM which illustrates how it leverages WPF data binding and commands.

The main difference between what we’re proposing and how they define MVVM in the previous articles is, by using a convention-based framework such as Caliburn.Micro and events/commands to wire up the View and ViewModel, they are completely decoupled allowing for better testability and future scalability. The Caliburn.Micro wiki has a good introduction to the functionality it provides.

This article gives a good introduction to Attribute Based Validation which allows us to keep validation logic down in the business layer and entities where it can then bubble up and be reflected in the UI.

If there’s interest in going deeper, here’s an article on using a Service Oriented Architecture (SOA) to decouple service providers from consumers allowing for greater reuse and insulating the application from core business logic.

Finally, a  series of articles outlining the use of a Generic Repository with Entity Framework 4 (EF4) to reduce the amount of plumbing that must be written and maintained for data access.



See also:
MVVM with WPF Series Part 1. Disconnected WPF Applications
MVVM with WPF Series Part 2. WPF MVVM with WinForms Controls

Friday, August 17, 2012

How much is experience worth?


During the Facebook IPO in May, UBS lost more than $350 million as a results of a glitch in their systems that re-sent buy orders and accumulated 40 million shares that would have to be sold at a loss.

As a software developer, it's not difficult to imagine the type of glitch that might cause such an issue. Something as small as comparing a value to null or improper error handling can cost a company hundreds of millions of dollars, which begs the question, how important are the architects and developers creating these systems?

It's easy to understand the importance of experience when building something as physically monumental as a sky scraper. People's lives depend on the quality of design and workmanship. Unfortunately, many companies don't see their enterprise software in the same light. They balk over the cost of senior talent and begrudge resources for quality control, then end up spending much more in damage control when systems fail.

How can we nurture a corporate culture that recognizes the value of experienced talent and proactive quality control?

Friday, August 10, 2012

You're Interviewing Them

Most of us are raised to believe that a job interview is where a potential employer asks you a bunch of questions to see if you're right for the job, but did you know that the best candidates often spend as much time asking questions as answering them?

Asking questions shows that you're serious about the job and indicates potential employment is as much your decision as it is theirs. Questions about culture and coworkers are a great way to take the focus off money and help the interviewer realize you're looking ahead to what employment with them might look like. A potential long-term employee wants to know if it will be a good fit and somewhere they will be happy working for an extended period of time.

Once an interviewer has established that you have the skills to do a job, the next question on their mind is usually performance. It's one thing to have ability, but quite another to have work ethic and focus. By asking about their top performers you can show your interest in becoming one of them. By keeping the question open ended, such as "What is the most important quality you see in your top employees?", you can gain insight into what's most important to them and provide examples of how you've displayed said quality later in the interview.

Asking the right question isn't just about gathering information and doesn't replace the need for preparatory research. In fact, it's vital to have a basic understanding of the company's business in order to know what questions to ask. One example is the question, "How do you deal with [insert challenge here]?" Addressing a challenge facing the business not only shows you've done your homework, but it also indicates you're a problem solver and interested in being part of the solution.

Some questions depend on the interviewer. When being interviewed by someone from human resources it is probably best to keep questions general with focus on the overall company and position in question. With a hiring manager you're able to delve deeper into how they measure success and what they need most in an employee. The best opportunity for information gathering, however, comes when interviewing with a peer. Asking about their experiences with that company and manager not only provides valuable insight into the position, but shows respect for their opinion which can be very endearing.

Good questions don't take the place of being qualified and informed, but they are a great way to make yourself stand out from the crowd and determine if this specific opportunity is right for you.

Thursday, August 9, 2012

WPF MVVM with WinForms Controls

This is the second part of my series on using MVVM with WPF. In the first article I discussed architecting disconnected applications and how MVVM was a great fit for WPF smart clients as well as Silverlight web clients. Now we move on to the process of refactoring an old Windows Forms application to use this new architecture.

The main concern with changing an underlying technology is the initial investment in rewriting code. To help mitigate this issue, WPF has provided a WindowsFormsHost element that allows us to host WinForms controls inside of a WPF Page. Obviously this limits how effectively we can leverage other features provided by WPF, however with a few workarounds it's a viable solution to avoid having to completely rewrite those old WinForms controls.

How easy is it to implement the WindowsFormsHost?
<WindowsFormsHost><wfh:WinFormsUserControl x:Name="LegacyUserControl" /></WindowsFormsHost>

Okay, it's only slightly more complicated than that. You will need to add add a reference to WindowsFormIntegration and possibly System.Windows.Forms (if it is not already referenced).

Now the question comes to how we interact with this control from our ViewModel since we can't use WPF bindings in our WinForms control. We can bridge this gap by adding events to our WinForms user control.


Then we wire up the events to our DataContext in our WPF Page code-behind.


While I generally prefer to avoid using the code-behind, we also don't want our ViewModel to be aware of the internal workings of our View.

The end result is our Windows Forms control interacts with elements in our WPF Page.

demonstration

Download Demo Source Code

Tuesday, July 24, 2012

Disconnected WPF Applications

I was recently tasked with presenting a plan to turn an existing WinForms program into an enterprise level application. They wanted to stick with a Windows client, but since each form would already need significant rework to extract the business logic, I suggested moving to WPF using the Model-View-ViewModel (MVVM) presentation pattern.

MVVM is basically a type of Model-View-Presenter (MVP) pattern that makes use of declarative bindings. State and logic are stored in the Presenter (ViewModel) which presents an abstract view of the UI with no knowledge of what View will implement it.

With the Presentation Layer taken care of, it was time to address the heart of the Application. The immediate need was for a smart client, however the solution was still very young and continually changing so it seemed a Service Oriented Architecture (SOA) would provide the most flexability and reuse. The question was how a disconnected client would use services.

Microsoft used to offer an application block for this specific purpose. The Disconnected Service Agent Application Block helped maintain a queue of web service requests while working disconnected (offline), then submit them to the server when it became available. Unfortunately, it is no longer being maintained and I have not found a suggested replacement. My guess is that they would encourage use of Sync Framework, which is designed to synchronize databases and files, but can use custom providers as well.

We're using Sync Framework to replicate data down to the client for offline use, but to utilize SOA and keep business logic/validation on the server we need a way of queuing web service calls and resolving any conflicts that occur. I'm currently in the process of researching whether a Sync Framework custom provider would be a good fit or if the old disconnected service agent application block would be a good starting point.

The existing relies very heavily on SQL stored procedures. Fortunately, Entity Framework (EF4) supports calling the existing stored procedures so they wont all have to be rewritten immediately. The plan is to gradually move business logic up into the application layer and use entity model. I've also added a generic repository to allow mocking.

I welcome feedback and suggestions. If you've tinkered with custom providers for Sync Framework or have suggestions for how to best queue and resolve service calls I'd love to hear from you, either by leaving a comment below or on twitter (@gainesk).

Thursday, July 19, 2012

Water pressure issues? Let it flow!

Most of my articles are about technology and software development, however I recently purchased a new home and, as I worked on various things around the house I realized others might benefit from a few of the more common issues I've addressed. Some of these problems might seem simple to fix, however I figure there are others like me who are learning these things for the first time and might find my experiences helpful.

Problem: Water pressure is fine at first, but within a few seconds flow decreases significantly. The hot water never gets beyond warm, but both hot and cold suffer from the same decreased flow.

Diagnosis: It's important to distinguish between water pressure and volume. Low water pressure results in a lower flow as soon as valve is opened. This can result from undersized pipes or the use of valves/connections that reduce flow as well as simply receiving low pressure from the source. A volume issue results from some restriction farther down the line that allows a higher pressure to build over time, but once that pressure is released (such as in the first few seconds of running water) then the pressurized volume is exhausted and flow is limited by the restriction. If both hot and cold lines suffer from the same symptoms then the problem most likely exists on the main water line before the water heater.

Solution: Every situation is different, but in my case I found that the main cutoff valve at the meter box was not completely open. One and a half turns more and the restriction was gone restoring full flow to the house.

If you've run into a similar problem I'd love to hear about it. Comments are appreciated and you can find me on twitter (@gainesk).

Friday, June 8, 2012

Should Internet Access be a Right?

Internet access has become a mainstay of our society and arguably more important to staying informed and the ability to make a living than phone or television. It's something that can be taken for granted when living in a densely populated city, but many rural areas are left with spotty or non-existent broadband service. For software developers in particular this can make working remotely and offering after-hours support difficult or even impossible.

I'm all for capitalism and a competitive market and I understand that most utility/service companies are out to make a profit so providing service to new areas is something they have to consider carefully, however when it comes to regional services these companies often have a monopoly that discourages new competitors and leaves residents with limited choices, and sometimes no choice at all. That's one reason why companies are often required to sign franchise agreements with city, county or state where they agree to provide a certain level of service in exchange for their territory.

For example, Comcast signed a franchise agreement with Franklin County (TN) which states they will, "provide Cable Service to every dwelling unit wtihin the Franchise Area reaching the minimum density of at least twenty-five (25) dwelling units per mile". To put this in perspective, if you split one square mile up into equal lots then each resident would have approximately 25 acres. This means that they have committed to providing service to all but the most rural and sparsely populated areas.

One important point regarding this agreement is that it only addresses Cable Service, which is defined as, "(A) the one-way transmission to Customers of (i) video programming, or (ii) other programming service, and (B) Customer interaction, if any, which is required fo rthe selection or use of such video programming or other programming service." While it makes sense they would offer additional services once the company has invested in running lines out to new areas, they have no commitment to providing internet access.

Does the area you live in have a franchise agreement with local internet service providers? Do you think that internet access is something they should be required to provide to residents or is it a luxury?

Tuesday, May 15, 2012

Using ODAC with EF4 via WCF

Oracle Data Access Components (ODAC) 11.2 Release 4 (11.2.0.3.0) with Oracle Developer Tools for Visual Studio includes support for Entity Framework and LINQ. Implementation is simple, however when I called the query from a WCF service I got the error:

System.ArgumentException was unhandled by user code
  Message=The specified store provider cannot be found in the configuration, or is not valid.
  Source=System.Data.Entity
  StackTrace:
       at System.Data.EntityClient.EntityConnection.GetFactory(String providerString)
       at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
       at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName)
       ...
  InnerException: System.ArgumentException
       Message=Unable to find the requested .Net Framework Data Provider.  It may not be installed.

A bit of research discovered that 32-Bit Applications are disabled by default in the IIS Application Pool. As soon as I changed Enable 32-Bit Applications to True everything worked fine.


Tuesday, May 8, 2012

Testing the Untestable with VS2012 Fakes

One of the new features included with Visual Studio 2012 is the Fakes Framework which offers the ability to detour code at runtime and isolate functionality for true unit testing, regardless of whether the code was written with testing in mind.

I began speaking on Fakes back when it was a beta product from Microsoft Research called Moles. While the core functionality remains the same, Microsoft has streamlined the implementation and now calls the detour mechanism a shim rather than a mole.

If you have attended this or another of my talks at a user group or conference, please take a moment to share your feedback on SpeakerRate.

The PowerPoint is available on SlideShare and below are links to the code demonstrated in the presentation.

Demos
Y2K Checker (simple introduction)
DateTime Audit (avoiding non-deterministic tests)
File Reader (shimming file system access)
Repository (stubbing interfaces)

Resources
Visual Studio 2011
Fakes MSDN Documentation

Friday, March 16, 2012

Ignite Talk on Gaming

I signed up to give an Ignite talk this evening on why everyone should play games. For anyone who's not familiar with Ignite talks, presenters share a personal or professional passion, using 20 slides that auto-advance every 15 seconds for a total of five minutes.

My slides can be found on my SlideShare profile:
http://www.slideshare.net/gaines/ignite-reasons-to-play-games

If you attended one of my talks, please feel free to provide feedback at SpeakerRate:
http://speakerrate.com/gaines

Tuesday, February 21, 2012

Truncating Text by Pixel Width

If you've ever tried truncating text by the number of characters then you've probably noticed that most of the fonts we use are not fixed-width, resulting in different lengths depending on which characters are used. This is particularly true of spaces which are much thinner than other characters.



I ran into this problem recently when creating a message preview module and I solved it by placing the text in a hidden div set to my desired width, then chopping off characters from the end until it fit. Of course, we don't want partial words so I wait until we reach a space before returning the truncated text.

Here is the div (placed in the page body):
<div id="hiddenTruncateHelper" style="position: absolute; visibility: hidden; display: block; height: auto;"></div>

...and the JavaScript:
var truncate = function (str, width, height) {
    var bits, bit, i;
    $("#hiddenTruncateHelper").width(width);
    $("#hiddenTruncateHelper").text(str);
    bits = str.split('');
    if ($("#hiddenTruncateHelper").getHiddenDimensions().height > height) {
        for (i = bits.length - 1; i > -1; --i) {
            $("#hiddenTruncateHelper").text(bits.join(''));
            bit = bits[i];
            bits.length = i;
            if (' ' === bit && $("#hiddenTruncateHelper").getHiddenDimensions().height <= height) {
                break;
            }
        }
    }
    return bits.join('');
};

One problem I had was that the browser kept returning zero for the div height because it is hidden. While searching for an answer I found a blog by Tim Banks where he shares an extension method to get the dimensions for a hidden element.
//Optional parameter includeMargin is used when calculating outer dimensions
(function ($) {
    $.fn.getHiddenDimensions = function (includeMargin) {
        var $item = this,
        props = { position: 'absolute', visibility: 'hidden', display: 'block' },
        dim = { width: 0, height: 0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 },
$hiddenParents = $item.parents().andSelf().not(':visible'),
includeMargin = (includeMargin == null) ? false : includeMargin;

        var oldProps = [];
        $hiddenParents.each(function () {
            var old = {};

            for (var name in props) {
                old[name] = this.style[name];
                this.style[name] = props[name];
            }

            oldProps.push(old);
        });

        dim.width = $item.width();
        dim.outerWidth = $item.outerWidth(includeMargin);
        dim.innerWidth = $item.innerWidth();
        dim.height = $item.height();
        dim.innerHeight = $item.innerHeight();
        dim.outerHeight = $item.outerHeight(includeMargin);

        $hiddenParents.each(function (i) {
            var old = oldProps[i];
            for (var name in props) {
                this.style[name] = old[name];
            }
        });

        return dim;
    }
} (jQuery));

That's all there is to it. We just call our method and pass in the string, desired height and width (in pixels) and it returns the truncated text. Just add some ellipses with a tooltip (title) and we're done!
<a href="#" title="FULL TEXT">...</a>

If you have a suggestion for how this solution could be improved or a question, please post it here. Thanks for reading!

Thursday, February 9, 2012

Microsoft PEX and Moles

Microsoft Research is currently beta testing a couple new frameworks that can make unit testing your code a breeze. Pex is a testing tool that analyzes code and generates unit tests. Moles is a framework that isolates code with dependencies on other application layers or frameworks. With just a few mouse clicks, you can generate suites of tests against code that previously may have been difficult or impossible to test.

Tonight I'll be giving a presentation on these technologies at the Nashville .NET User Group. For anyone who can't make it you can watch and discuss it in my Google Hangout. I'm hoping to post a video of the presentation to this blog within the next couple weeks. I'll also be giving a similar presentation and Code PaLOUsa on March 17th. Below are links to the demo solutions and Prezi used in the presentation.

Presentation on Prezi
Using Moles to Mock DateTime (Y2KBug.zip)
Using Moles to Stub Interfaces (MolesDemo.zip)
Using PEX to Generate Parameterized Unit Tests (PEXDemo.zip, PEXDemo-Result.zip)