dotnetinterview v1.0.0 has been released today. You can download it here.
From the project description:
These are some coding problems designed for .NET developer candidates (although most could be adapted for any OO language). Sure, your candidates know C# but how well do they understand object-oriented programming? DRY? SOLID Principles? etc. Make sure your candidates will build a masterpiece, not a mess.
I have tried to make these problems simple yet deep. My goal is that one or more problems could be emailed to a potential candidate and completed relatively quickly. These are conversation starters meant to initiate dialog with potential hires, not a test.
This will be a continual work in progress. I plan on adding new problems on a frequent basis. There are no answers provided. If the candidate is able to Google his way through these problems, that is a Good Thing. It shows learning ability.
Since there are no "right" answers, an understanding of OOP is needed in order to administer these problems.
Need to practice your skills? Learn new technologies? Provide sample code to prospective employers? A code resumé handles all of that. I have been working on mine for a little while now, but it’s not ready for wide distribution. There just isn’t enough in there yet. Mine includes code katas, which mostly demonstrate my understanding of TDD and concepts like DRY, SOLID, etc. It also includes simple projects like WPF App using Prism and Entity Framework 4 and MVC App using NHibernate. These simple projects give you a chance to discuss your design decisions, TDD skillz, architecture or any other topic around application development that you deem important.
I will most likely host my code resumé on Google so that it is readily available to anyone. I suggest a project name of yourname with subfolders for each individual category and project. I don’t really care that everyone and their mom will be able to pull it down. I might get some good feedback and learn something in the process.
A nice thing about having a code resumé is that it can provide talking points for your interview. Hopefully, what this means is that you get a little more control over your technical interview. Show your future employers what you do know and get them talking to you about that instead of hoping you can answer their random bucket of questions. Better yet, bonus points if you can answer their questions by pointing to your code.
Download Code
A colleague and I were lamenting the sad state of technical interviews the other day and came to the conclusion that there must be a better way. The problem with many technical interviews (including the preliminary ones my company gives) is that they are not really testing the right things.
For instance, my company gives candidates a test that asks about a SortedList. Honestly, I had to look it up myself. Turns out it’s a Dictionary that has sorted keys. I have never used it and had no idea it was there. Does that make me a bad hire? Well, I don’t think so….but… The test also asks what the default access modifier of a method is. “I always specify access modifiers explicitly so my code is clear and concise” is not one of the answers on the test. But in my book, that’s the right answer.
The problem with these kinds of tests are two-fold. One, someone can come in knowing the C# language and the .NET Framework backwards and forwards (backed up with all kinds of certifications). But do they really understand anything about good program structure? Sure, they can use a hammer…but can they build a house? I need people on my team that can build houses. Two, these kinds of tests filter out people that you might really want to hire. Are you really going to reject someone because they don’t know what checked does?
I have started a small project called dotnetinterview. It’s just a repository of simple coding examples that can be given to potential hires. Each sample is fairly simple and designed to test one or more programming concepts: DRY, abstraction, encapsulation, polymorphism, SOLID principles, etc. As of now, I would say the project is in bad shape. Definitely a work in progress. But it will get better.
Mind you, there are no “answers”. As an interviewer, you would be expected to know what was being tested just by looking at the code. If you don’t know, you might not be in a position to give the test. I would consider these problems Google-proof (at the moment) and that means they can be emailed to a candidate before an interview. The beauty of this is that even if they “cheat” by talking to one of their super-smart programming buddies, they still will have learned something. Plus, the candidate is still expected to talk about their solution at the next interview.
Another nice thing is that some candidates might not know the names of things. If you go off talking about Fowler’s refactorings they might not know what you are talking about – even though they do it all the time. These problems give the candidate a chance to write good code without knowing what things are called.
Anyway, let’s look at a problem. Isn’t it simple? This type of problem is great for college hires.
using System;
namespace Interview.Questions
{
/*
Refactor to a more object-oriented style.
*/
public class Rectangle
{
public int Length { get; set; }
public int Width { get; set; }
}
public class RectangleProgram
{
public static void main()
{
Rectangle r = new Rectangle();
r.Width = 10;
r.Length = 20;
// calculate area
int area = r.Width*r.Length;
// output message
Console.WriteLine("[Width: {0}, Length: {1}, Area: {2}]",r.Width, r.Length, area);
}
}
}
Here’s another. This one is more complex. A knowledge of common refactorings and some design patterns will pay off here.
using System;
namespace Interview.Questions
{
/*
Develop abstractions and make it easier to modify vacation calculation rules
*/
public class VacationCalculator
{
public int Calculate(int employeeId,
string lastName,
string firstName,
bool isHourly,
bool isManager,
decimal baseSalary,
DateTime hireDate)
{
int days = 0;
if (!isHourly)
{
if (baseSalary >= 100000)
days += 14;
else
days += 7;
if (hireDate < DateTime.Now.AddYears(-3))
days += 14;
else
days += 7;
}
Console.WriteLine("Employee [" + employeeId + "]: " + lastName + ", " + firstName + " gets " + days + " vacation.");
return days;
}
}
}
Finally, here’s a third problem. Depending on who you are, these problems might be appear to be super-retarded. I’ve been involved with 20 or so interviews over the past two years. Trust me, they aren’t. Unfortunately.
using System;
using System.Collections.Generic;
namespace Interview.Questions
{
/*
How would you rewrite this code so that MessageClient could display IM messages as well as SMS messages?
Or Email messages? How can you make MessageClient easier to test?
*/
public class SMS
{
private readonly List<string> _messages = new List<string>();
public void AddMessage(string message)
{
_messages.Add(message);
}
public IList<string> GetMessages()
{
return _messages;
}
}
public class MessageClient
{
public void GetMessages()
{
SMS sms = new SMS();
foreach(var message in sms.GetMessages())
{
Console.WriteLine(message);
}
}
}
}
Many of these problems do not have a perfect answer either – you know, where everything is obviously beautiful by the end of the refactoring. They are really meant to give some context to an interview. It beats “when would you use an abstract base class instead of an interface?” any day.
I am probably going to try and build up a large collection of these things. I don’t really know how good they are in their current state, but I do feel like I am headed in the right direction, at least conceptually. If you have any problems you would like to contribute and you would like to help me build up the project, let me know.
I just checked the ReSharper 5.0 Nightly Builds. The comments for the 10/29 build says “Initial VS 2010 beta2 support”. I am installing this the second I get home.
Download Code Here
In my last article on printing labels, I used PDFsharp to do the heavy lifting. I thought it was a pretty good solution for someone who was stuck in .NET 2.0.
If you are not in that situation, I have a better solution: WPF. There are several classes available which make layout and printing very easy. Print preview is handled by a WPF control called DocumentViewer. I originally got the idea from Neodynamic. They have some sample code which is hard-coded to print sheets of Avery 5160 labels. I refactored their code, then rewrote the whole thing to be the starting point of a reusable library that can be used to print any size labels. But, kudos to them for the original idea.
Here’s how it works.
First, you need to create your actual label. This will be a WPF user control that is sized to the appropriate dimensions. You can layout the label anyway you want, of course. WPF uses 96 DPI internally (referred to as DIU for device independent units). So, label sizes in inches can use: inches * 96 to get the appropriate size in pixels. I’ll leave converting from cm and mm to you, the reader.
Figure 1. Label sized to 384 x 192 (4” x 2”).
After you design your label, you need to create a sheet to add them to. At the time of this writing, the library includes classes for Avery 5160, 5163, and 6873 labels, but defining your own sheets is easy. Just derive from LabelSheet and set the measurements in the constructor. Here’s the code for the Avery 6873 sheet. Notice that all measurements are entered in native units:
public class Avery6873 : LabelSheet
{
public Avery6873() : base(LabelUnit.Inches)
{
Rows = 4;
Columns = 2;
PaperSize = new Size(8.5, 11);
LabelSize = new Size(3.75, 2);
Gutter = new Gutter(.25, .25);
Margin = new Thickness(.375, 1.125, .375, 1.125);
}
}
The library comes with a form that will display the labels and handle printing them. All you need to do is create your list of labels. In this example, ShippingLabel is a label that I made. Next, pass the labels to LabelSheet.CreateDocument. The resulting FixedDocument can be passed right to the document viewer:
LabelViewer viewer = new LabelViewer();
List<ShippingLabel> labels = new List<ShippingLabel>();
Avery5163 avery = new Avery5163();
for(int i = 0; i < avery.LabelsPerSheet; i++)
{
ShippingLabel label =
new ShippingLabel
{
Return1 = { Text = "J.P. Hamilton" },
Return2 = { Text = "1313 Mockingbird Ln." },
Return3 = { Text = "Los Angeles, CA 90210" },
Line1 = { Text = "Microsoft" },
Line2 = { Text = "c\\o Bill Gates" },
Line3 = { Text = "1 Microsoft Way" },
Line4 = { Text = "Redmond, WA 98052" }
};
labels.Add(label);
}
viewer.Document = avery.CreateDocument(labels);
viewer.Show();
The end result looks like this:
I am not going to go over the technical aspects. That’s all in the code. Have a look at the LabelSheet class to see how it’s all done.
Lastly, one thing to remember when you print. Make sure that you have all auto-sizing features turned off. You will want to print the output at 100%.
Download Here
(this is another entry in my POC series – proof of concept, piece of crap…you decide)
In my current application, I need the ability to print labels – and I need something flexible, quick, and easy. I started down the path of using interop with Word and quickly decided that this approach completely sucks. It’s not flexible. It’s not quick. And it’s certainly not easy. What I settled on was creating the labels in a PDF and then printing from there. To handle PDF creation, I am using a really great library called PDFsharp. It’s API is similar to doing graphics with GDI+, so it took me no time at all to get started.
Now for the basics. I have a base class that allows me to define margins, gutters and other label-specific stuff:
/// <summary>
/// One or more sheets of labels
/// </summary>
public abstract class LabelSheet
{
public int Rows { get; set; }
public int Columns { get; set; }
public LabelSize Size { get; private set; }
public LabelMargin Margin { get; private set; }
public LabelGutter Gutter { get; private set; }
public IList<LabelBase> Labels { get; private set; }
protected LabelSheet()
{
Labels = new List<LabelBase>();
Size = new LabelSize();
Margin = new LabelMargin();
Gutter = new LabelGutter();
}
public void Print(ILabelPrintingStrategy printer)
{
printer.Print(this);
}
public void Print(ILabelPrintingStrategy printer, int startWithLabel)
{
printer.Print(this, startWithLabel);
}
public void Add(LabelBase label)
{
Labels.Add(label);
}
public void Add(LabelBase label, int count)
{
while (count-- > 0)
Add(label);
}
public int Count
{
get { return Rows*Columns; }
}
}
I found a site called WorldLabel.Com that has label information for every type of label you could ever want. So, armed with this, I can create specific sheets of labels like so:
/// <summary>
/// A sheet of Avery 5160 labels
/// </summary>
public class Avery5160Labels : LabelSheet
{
public Avery5160Labels()
{
Columns = 3;
Rows = 10;
Size.Length = 2.5935;
Size.Height = 1;
Margin.Top = 0.5;
Margin.Bottom = 0.5;
Margin.Left = .21975;
Margin.Right = .21975;
Gutter.Horizontal = 0.14;
Gutter.Vertical = 0;
}
}
One thing to note is that the class is currently using inches, because that’s how us Americans are used to dealing with labels. It should not take any effort at all to make this more flexible. I did not do so, because I do not have requirements for that yet, and I don’t feel like starting an open source project for printing labels.
Another thing to note is that LabelSheet has a method called Print that takes an ILabelPrintingStrategy. This interface defines two methods:
void Print(LabelSheet sheet);
void Print(LabelSheet sheet, int startWithLabel);
If you download the code, you will see a single strategy called PdfLabelPrintingStrategy. This class handles the grunt work of laying out the labels and writing them out to a PDF. The second overload of Print allows you to specify a starting label. So, if you have a half sheet of labels, you can start printing from the 15th label. In the demo code, I put together a quick and dirty UI that allows you to pick the starting label. I am sure you could find plenty of ways to improve this code, and I am sure that I will improve this code in the future. But this is what I have for now.
Download here
Warning: The current condition of the code is “proof of concept”. You have been warned. Also, naming conventions are not really good, okay?
The other day I was talking with a colleague about the idea of “searching as an architectural concern”. Sounds kind of pie-in-the-sky, I know, but the truth is that in most enterprisy applications we spend a lot of time looking for things: Employees, Requisitions, Contacts, you name it. And to be honest, I am pretty tired of writing this type of code. What I really want, is to be able to describe a search and then have a UI automagically rendered for me. I also want to have some sort of pipeline from there that takes care of all the grunt work. So, for instance, if I want to search for an Employee, I can do something like this:
public class EmployeeSearchViewModel : SearchViewModel<Employee>
{
public EmployeeSearchViewModel(SearchView view) : base(view)
{
IList<NameValuePair> lookups =
new List<NameValuePair>
{
new NameValuePair() {Name = "", Value = null},
new NameValuePair() {Name = "North", Value = "N"},
new NameValuePair() {Name = "South", Value = "S"},
new NameValuePair() {Name = "East", Value = "E"},
new NameValuePair() {Name = "West", Value = "W"}
};
// these are the fields the user can use to build a query
search.AddQuery("Last Name", x => x.Last);
search.AddQuery("First Name", x => x.First);
search.AddQuery("Date Hired", x => x.DateHired);
search.AddQuery("Sales Region", x => x.Region, lookups);
search.AddQuery("Street", x => x.Address.Street);
// these are the values that are shown in the results
search.AddResult(x => x.Last, "Last Name", 150);
search.AddResult(x => x.First, "First Name", 100);
search.AddResult(x => x.DateHired, "Date Hired", "MM/dd/yyyy", 75);
search.AddResult(x => x.Region, "Sales Region", lookups, 100);
}
protected override void OnOk()
{
EmployeeRepository repository = new EmployeeRepository();
Results = repository.Find(search);
}
}
Which will give me something like this (but with much better styling than is shown here):
Essentially, this view is rendered for me based on what I have described in code. Let’s go over the highlights.
Search.AddQuery specifies which properties on Employee that I want to expose to the search criteria. Everything is type-safe, too. So, to add last name, first name, and date hired, I do this:
search.AddQuery("Last Name", x => x.Last);
search.AddQuery("First Name", x => x.First);
search.AddQuery("Date Hired", x => x.DateHired);
What may not be obvious is that the UI will render itself differently based on the data type. For instance, Employee.Last and Employee.First are strings. This means that the operator dropdown will contain: =, <>, Contains, Starts With, Ends With (you could add more). The input control is rendered as a textbox. Since Employee.DateHired is a DateTime, the condition dropdown will contain a different set of operators: =, <, >, <=, >=. In other words, the operators that make sense for a date. The input control will be rendered as a DatePicker (WPF Toolkit). FYI, this is done using data template selectors in XAML.
Lookups and child objects can also be used:
search.AddQuery("Sales Region", x => x.Region, lookups);
search.AddQuery("Street", x => x.Address.Street);
Here, I’ve said that I want to allow the user to search by Sales Region, but I want to present the choices in a dropdown which is bound to lookups (in this case an IList<NameValuePair>). Searching on child objects, like Employee.Address, works just like anything else. Nice!
The search will return an IList<Employee> representing the results of the query. All that needs to be done, is to declare which properties on Employee will be displayed:
search.AddResult(x => x.Last, "Last Name", 150);
search.AddResult(x => x.First, "First Name", 100);
search.AddResult(x => x.DateHired, "Date Hired", "MM/dd/yyyy", 75);
search.AddResult(x => x.Region, "Sales Region", lookups, 100);
Search.AddResult allows you to specify the property (think column header here), the friendly name (for label captions), column width of output, data format, and lookups (in this case for translating “N” to “North” for display purposes).
Building Expressions
In the ViewModel, the search has been defined by calling Search.AddQuery and Search.AddResult. Search exposes another property called Criteria, which is actually an IList<Criteria> – confusing I know (remember what I said about the naming conventions back at the beginning?) This list will contain one Criteria object for every AddQuery call. Criteria contains the name of the underlying property, the operator that was selected in the dropdown and the value entered by the user. This list of Criteria is bound to the UI like so:
<ItemsControl Grid.Row="1"
ItemsSource="{Binding Criteria}"
Background="Bisque"
ItemTemplateSelector="{StaticResource searchTemplateSelector}"/>
Bisque – you gotta love it!
When the user presses the Search button, each Criteria object is converted into a Predicate<T>. Or in this, example, a Predicate<Employee>. These Predicate<T> objects will be used later on to build up the WHERE clause of a LINQ expression which will ultimately do the real work. In the POC, a Repository is used that accepts the Search object outright:
protected override void OnOk()
{
EmployeeRepository repository = new EmployeeRepository();
Results = repository.Find(search);
}
Ultimately, LINQ is used to get the results. In the POC, the data source is just a prebuilt IList<Employee>, which is why a “source” is being passed in:
protected IList<T> Find(Search<T> search, IEnumerable<T> source)
{
IEnumerable<T> results = source;
foreach (var condition in search.Conditions)
{
results = results.Where(x => condition(x));
}
return results.ToList();
}
However, it should be easy to adapt this concept to any ORM with a LINQ provider (LINQ to SQL, NHibernate, LightSpeed, etc). If LINQ to SQL were the ORM, Find might look something like this (not too much different than the POC):
protected IList<T> Find<T>(Search<T> search) where T:class, ITable
{
using (var dc = CreateContext())
{
IQueryable<T> results = dc.GetTable(typeof(T));
foreach(var condition in search.Conditions)
{
results = results.Where(x => condition(x));
}
return results.ToList();
}
}
That’s all I’ve got. I know it’s rough. But I am sure that somebody out there could take this pretty far.
It’s a little ditty I wrote called Exit Deluxe. It’s just like the current Exit command, but better. And it’s so easy to make, that I am going to show you how to code it yourself.
Step 1: Create a new Add-In Project called “Exit Deluxe”
Step 2: Follow the friendly wizard all the way to the end. Pick whatever options you want.
Step 3: Open up Connect.cs, and add the following lines of code to the Exec method (with 3 ref parameters – stay classy MS):
public void Exec(string commandName,
vsCommandExecOption executeOption,
ref object varIn,
ref object varOut,
ref bool handled)
{
handled = false;
if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
{
if(commandName == "ExitDeluxe.Connect.ExitDeluxe")
{
var process = System.Diagnostics.Process.GetCurrentProcess();
process.Kill();
handled = true;
return;
}
}
}
Step 4: Compile, you’re done.
Now, any time that you want to exit Visual Studio, you go to Tools->Exit Deluxe and you get a wait-free shut down.
Note: We can have the argument about MVVM really being Presentation Model later :) I just use MVVM here because it makes the title of this post a little shorter.
I was reading about Josh Smith’s MVVM Foundation library today. It looked interesting, so I downloaded it to look at some of his classes. One thing that jumped out at me was his ViewModelBase class. When compiled to debug, there are some checks performed to make sure that the strings being passed in to the INotifyPropertyChanged implementation are valid.
This started me thinking about an approach that I have been using recently, which allows me to implement INotifyPropertyChanged in a type-safe way. Here are the relevant parts of my base class:
public abstract class ViewModel<MODEL> : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged<R>(Expression<Func<MODEL,R>> x)
{
var body = x.Body as MemberExpression;
if (body == null)
throw new ArgumentException("'x' should be a member expression");
string propertyName = body.Member.Name;
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
}
The method signature of RaisePropertyChanged is strange indeed. What I like is that the compiler is smart enough to deduce R, so I don’t need to specify it in the call, which looks like this:
RaisePropertyChanged(employee => employee.LastName);
No more magic strings!
I have heard many times that tests are like documentation for other developers. The argument is that formal documentation (word documents, spreadsheets, etc.) rarely stays in sync with the current state of an application. Therefore, unit tests act as a kind of up to date documentation (provided that the tests are all passing, of course). Tests tell developers who are not familiar with the code, how an application should work and what the expectations are. But consider this test:
[TestFixture]
public class when_user_is_logging_in
{
[Test]
public void only_three_login_attempts_are_allowed()
{
ILoginView view = MockRepository.GenerateStub<ILoginView>();
view.Stub(x => x.User).Return("bad");
view.Stub(x => x.Password).Return("bad");
ILoginService loginService = MockRepository.GenerateMock<ILoginService>();
loginService.Expect(x => x.UserExists("bad", "bad")).Return(false);
LoginPresenter presenter = new LoginPresenter(loginService);
presenter.Initialize(view);
view.Raise(x => x.TryLogin += null, this, EventArgs.Empty);
view.Raise(x => x.TryLogin += null, this, EventArgs.Empty);
view.Raise(x => x.TryLogin += null, this, EventArgs.Empty);
view.AssertWasCalled(x => x.Close());
}
}
Right away it’s pretty clear that “when a user is logging in, only three login attempts are allowed”. But things quickly go south after that. What mocking frameworks give us in convenience, they sure take away in readability. Regarding the above example - it’s written using Rhino Mocks 3.5. Many developers not familiar with mocking may be surprised to learn that this is actually the “good” syntax. Things used to be a heck of a lot worse. However, I still think that there are some things that could be done to clean these tests up, while still adhering to spirit of “tests that act like documentation”. My goal here, is to do this with as little ceremony as possible. I am not interested in writing a whole lot of new code in order to achieve readability. I just want to explore some simple ideas. When looking at the examples here, try to consider that there may be 10 or more additional tests which are not being shown. This will give you a better gauge as to whether the effort expended here is really worth it.
The Clean Up
ILoginView have User and Password properties that needs to return different values depending upon the test. To clean up the current implementation, we could do something over-the-top, like this:
// add this method to test class
private static ILoginView CreateLoginView
{
get
{
return MockRepository.GenerateStub<ILoginView>();
}
}
// add internal class to hold extension methods
internal static class when_user_is_logging_in_extensions
{
public static ILoginView WithUser(this ILoginView view, string user)
{
view.Stub(x => x.User).Return(user);
return view;
}
public static ILoginView AndPassword(this ILoginView view, string password)
{
view.Stub(x => x.Password).Return(password);
return view;
}
}
// Now, I have a readable fluent interface
ILoginView view = CreateLoginView.WithUser("BADUSER").AndPassword("BADPASSWORD");
Readable, sure, but seriously, that’s a lot of code. All of the convenience of using Rhino Mocks is lost. To compromise, I would probably just do something like this:
// in test class
private static ILoginView CreateLoginView(string withUser, string withPassword)
{
ILoginView view = MockRepository.GenerateStub<ILoginView>();
view.Stub(x => x.User).Return(withUser);
view.Stub(x => x.Password).Return(withPassword);
return view;
}
// in test
ILoginView view = CreateLoginView("BadUser", "BadPassword");
Here, I will let the method name, parameter names, and IntelliSense act as documentation. Like the last example, it requires a bit of code, too, but in this case ReSharper handles the Extract Method for me. Renaming CreateLoginView to create_login_view makes the IntelliSense story even better (in my opinion), but I will leave that alone for now.
For the login service, I will use the same technique:
// in test class
private static ILoginService CreateLoginService(bool shouldAuthenticate)
{
var loginService = MockRepository.GenerateStub<ILoginService>();
loginService.Expect(x => x.UserExists("", ""))
.IgnoreArguments()
.Return(shouldAuthenticate);
return loginService;
}
// in test
ILoginService loginService = CreateLoginService(false);
To finish up, I will add a few extension methods by creating an internal static class at the bottom of my test file:
internal static class when_user_is_logging_in_extensions
{
public static void PushOkButton(this ILoginView view)
{
view.Raise(x => x.TryLogin += null, view, EventArgs.Empty);
}
public static void ShouldBeClosed(this ILoginView view)
{
view.AssertWasCalled(x => x.Close());
}
}
With all of the changes in place, my test now looks like this:
[Test]
public void only_three_login_attempts_are_allowed()
{
ILoginView view = CreateLoginView("BadUser", "BadPassword");
ILoginService loginService = CreateLoginService(false);
LoginPresenter presenter = new LoginPresenter(loginService);
presenter.Initialize(view);
view.PushOkButton();
view.PushOkButton();
view.PushOkButton();
view.ShouldBeClosed();
}
I am not advocating that anyone go to this trouble; context, preference, and discretion must be considered. However, I think there is great value in having readable tests. For some, the starting example might be perfectly readable. For others, not so much. As with everything, take what you like and leave the rest.