pr0g33k

 collapse all
  1. Simple CAPTCHA for MVC

    I recently overhauled this blog so that I could convert everything to MVC 5 and Entity Framework 6. While I was at it, I removed the ASP.NET Membership system and simplified the comment process. I had two reasons for doing this: 1) the new Membership system blows and 2) the Russians. You see, I was getting between 10 and 50 new member notifications every day - the vast majority of which were SPAM bots using ".ru" email addresses. It became clear that I'd have to implement something to counter the spammers.

    I searched for half a day looking for a CAPTCHA that looked good, was easy to implement, and was MVC-friendly. Surprisingly, I didn't really find much. I looked at reCAPTCHA but didn't really like its aesthetics or its implementation. There are several blog posts, CodeProject articles, and NuGet packages for CAPTCHA but most of their implementations rely on session variables to transport the CAPTCHA value - something I wanted to avoid. Writing my own ended up being pretty simple and, so far, very effective.

    The interface for the CAPTCHA is pretty simple. There's a challenge (the characters on the image that the user needs to type into a form field) and a response (the user's input).

    public interface ICaptcha
    {
        String Challenge { get; set; }
        String Response { get; set; }
    }

    For the implementation, I used the Random class to select from a string of characters and then used UrlTokenEncode to encode the challenge. I used UrlTokenEncode because I'll be creating an image request to a MVC action and pass the encoded challenge in the URL. UrlTokenEncode does a nice job of munging the characters and makes it safe for use in the URL. Also note that the characters I use do not include the letters "I" or "O" nor the numbers "1" or "0" so that there's no confusion among them when the characters are rendered in the image.

    public class Captcha : ICaptcha
    {
        private const Int32 TEXT_LENGTH = 5;
        private const String TEXT_CHARS = "ACDEFGHJKLNPQRTUVXYZ2346789";
        private Random _Random;
    
        public Captcha()
        {
            _Random = new Random();
            Challenge = HttpServerUtility.UrlTokenEncode(System.Text.UTF8Encoding.ASCII.GetBytes(GenerateChallenge()));
        }
    
        public String Challenge { get; set; }
    
        [CaptchaValidator]
        public String Response { get; set; }
    
        private String GenerateChallenge()
        {
            StringBuilder stringBuilder = new StringBuilder(TEXT_LENGTH);
    
            for (Int32 i = 0; i < TEXT_LENGTH; i++)
                stringBuilder.Append(TEXT_CHARS.Substring(_Random.Next(TEXT_CHARS.Length), 1));
    
            return stringBuilder.ToString();
        }
    }
    

    The user's response is validated using a custom ValidationAttribute. Although the characters are rendered as upper-case characters, case is ignored when validating the user's input.

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class CaptchaValidatorAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(Object value, ValidationContext validationContext)
        {
            if (validationContext.ObjectType.Name != "Captcha")
                return new ValidationResult("This attribute is being used incorrectly");
    
            if (value == null)
                return new ValidationResult("You must enter the CAPTCHA characters in the image");
    
            if (0 != String.Compare(UTF8Encoding.ASCII.GetString(HttpServerUtility.UrlTokenDecode(((Captcha)validationContext.ObjectInstance).Challenge)), value.ToString(), true))
                return new ValidationResult("CAPTCHA is not valid");
    
            return ValidationResult.Success;
        }
    }
    

    To help out on the MVC side of things, I created a HtmlHelper extension to handle the image tag and the hidden field to pass the encoded challenge upon HTTP posts.

    public static class HtmlHelperExtensions
    {
        public static MvcHtmlString Captcha<TModel, TProperty>(this System.Web.Mvc.HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, String action, String controller) where TProperty : ICaptcha
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            String htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            String propertyName = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last(); 
    
            TModel model = (TModel)html.ViewContext.ViewData.ModelMetadata.Model;
            TProperty captcha = expression.Compile().Invoke(model);
    
            UrlHelper urlHelper = new UrlHelper(html.ViewContext.RequestContext);
            String url = urlHelper.Action(action, controller, new { id = captcha.Challenge });
    
            return new MvcHtmlString(String.Format("<img src=\"{0}\" alt=\"CAPTCHA\" /><input id=\"{1}_Challenge\" name=\"{1}.Challenge\" type=\"hidden\" value=\"{2}\" />", url, propertyName, captcha.Challenge));
        }
    }

    The HtmlHelper accepts the model's Captcha property via an expression as well as values for the action and controller of the MVC controller method that's called to generate the image. Here's a sample of what that controller might look like:

    public class CaptchaController : Controller
    {
        public FileContentResult Image(String id)
        {
            return File(new CaptchaImage(id).ImageBytes, "image/jpeg");
        }
    }

    The CaptchaImage class accepts the encoded challenge, decodes it, and renders it onto an image. To make it difficult for OCR readers, I use random fonts, colors, transforms, and background noise.

    public class CaptchaImage
    {
        private readonly String _Text;
        private readonly Random _Random;
        private readonly Int32 _Height;
        private readonly Int32 _Width;
        private readonly String[] _RandomFontFamily = { "arial", "arial black", "comic sans ms", "courier new", "lucida console", "lucida sans unicode", "microsoft sans serif", "tahoma", "times new roman", "trebuchet ms", "verdana" };
        private readonly Color[] _RandomColor = { Color.Red, Color.Green, Color.Blue, Color.Black, Color.Purple, Color.Orange };
    
        public CaptchaImage(String text, Int32 height = 60, Int32 width = 300)
        {
            _Random = new Random();
            _Text = UTF8Encoding.ASCII.GetString(HttpServerUtility.UrlTokenDecode(text));
            _Height = height;
            _Width = width;
        }
    
        public Byte[] ImageBytes { get { return GenerateImageBytes(); } }
    
        private Byte[] GenerateImageBytes()
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (Bitmap bitmap = new Bitmap(_Width, _Height, PixelFormat.Format24bppRgb))
                {
                    using (Graphics graphics = Graphics.FromImage(bitmap))
                    {
                        graphics.SmoothingMode = SmoothingMode.AntiAlias;
                        graphics.Clear(Color.White);
    
                        Int32 charOffset = 0;
                        Double charWidth = _Width / _Text.Length;
                        Rectangle charRectangle;
    
                        Rectangle rectangle = new Rectangle(new Point(0, 0), bitmap.Size);
                        Int32 density = 18;
                        Int32 size = 40;
    
                        using (SolidBrush brush = new SolidBrush(Color.Gray))
                        {
                            Int32 max = Convert.ToInt32(Math.Max(rectangle.Width, rectangle.Height) / size);
    
                            for (Int32 i = 0; i <= Convert.ToInt32((rectangle.Width * rectangle.Height) / density); i++)
                                graphics.FillEllipse(brush, _Random.Next(rectangle.Width), _Random.Next(rectangle.Height), _Random.Next(max), _Random.Next(max));
                        }
    
                        Int32 length = 5;
                        PointF[] pointF = new PointF[length + 1];
                        using (Pen p = new Pen(GetRandomColor(), Convert.ToSingle(_Height / 27.7777)))
                        {
                            for (Int32 i = 0; i <= length; i++)
                                pointF[i] = RandomPoint(rectangle);
    
                            graphics.DrawCurve(p, pointF, 1.75F);
                        }
    
                        foreach (Char character in _Text)
                        {
                            using (Font font = new Font(_RandomFontFamily[_Random.Next(0, _RandomFontFamily.Length)], Convert.ToInt32(_Height * 0.85), FontStyle.Bold))
                            {
                                using (Brush fontBrush = new SolidBrush(GetRandomColor()))
                                {
                                    charRectangle = new Rectangle(Convert.ToInt32(charOffset * charWidth), 0, Convert.ToInt32(charWidth), _Height);
    
                                    StringFormat stringFormat = new StringFormat();
                                    stringFormat.Alignment = StringAlignment.Near;
                                    stringFormat.LineAlignment = StringAlignment.Near;
    
                                    GraphicsPath graphicsPath = new GraphicsPath();
                                    graphicsPath.AddString(character.ToString(), font.FontFamily, (Int32)font.Style, font.Size, charRectangle, stringFormat);
    
                                    Single warpDivisor = 5F;
                                    Single rangeModifier = 1.3F;
                                    RectangleF rectangleF = new RectangleF(Convert.ToSingle(charRectangle.Left), 0, Convert.ToSingle(charRectangle.Width), charRectangle.Height);
                                    Int32 hRange = Convert.ToInt32(charRectangle.Height / warpDivisor);
                                    Int32 wRange = Convert.ToInt32(charRectangle.Width / warpDivisor);
                                    Int32 left = charRectangle.Left - Convert.ToInt32(wRange * rangeModifier);
                                    Int32 top = charRectangle.Top - Convert.ToInt32(hRange * rangeModifier);
                                    Int32 width = charRectangle.Left + charRectangle.Width + Convert.ToInt32(wRange * rangeModifier);
                                    Int32 height = charRectangle.Top + charRectangle.Height + Convert.ToInt32(hRange * rangeModifier);
    
                                    if (left < 0)
                                        left = 0;
    
                                    if (top < 0)
                                        top = 0;
    
                                    if (width > _Width)
                                        width = _Width;
    
                                    if (height > _Height)
                                        height = _Height;
    
                                    PointF leftTop = RandomPoint(left, left + wRange, top, top + hRange);
                                    PointF rightTop = RandomPoint(width - wRange, width, top, top + hRange);
                                    PointF leftBottom = RandomPoint(left, left + wRange, height - hRange, height);
                                    PointF rightBottom = RandomPoint(width - wRange, width, height - hRange, height);
                                    PointF[] points = new PointF[] { leftTop, rightTop, leftBottom, rightBottom };
    
                                    Matrix matrix = new Matrix();
                                    matrix.Translate(0, 0);
    
                                    graphicsPath.Warp(points, rectangleF, matrix, WarpMode.Perspective, 0);
    
                                    graphics.FillPath(fontBrush, graphicsPath);
    
                                    charOffset += 1;
                                }
                            }
                        }
    
                        bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    
                        return memoryStream.ToArray();
                    }
                }
            }
        }
    
        private Color GetRandomColor()
        {
            return _RandomColor[_Random.Next(0, _RandomColor.Length)];
        }
    
        private PointF RandomPoint(Int32 xMin, Int32 xMax, Int32 yMin, Int32 yMax)
        {
            return new PointF(_Random.Next(xMin, xMax), _Random.Next(yMin, yMax));
        }
    
        private PointF RandomPoint(Rectangle rectangle)
        {
            return RandomPoint(rectangle.Left, rectangle.Width, rectangle.Top, rectangle.Bottom);
        }
    }

    Here is a sample MVC project. Let me know what you think!

  2. Getting Started: MVC 4, Entity Framework 5 Code First, and Unity

    After several hours of banging my head against the wall, I finally have a good, working prototype for using Entity Framework 5 Code First in a MVC application with the Unity Inversion of Control (IoC) container for dependency injection. (Say that 3 times fast!) I'm using an IoC container for a couple of reasons. For one, it'll allow me to (somewhat) easily swap out components if I want. For example, if I want to use nHibernate for data access instead of Entity Framework, all I'll need to do is change to what the context, IRepository, and IUnitOfWork interfaces resolve. All of the code I write in the Controllers or elsewhere can stay the same. Another reason I want to use an IoC is because it'll make my components (somewhat) easy to mock (or fake) to supply a way to perform integration tests without having to use the actual services (e.g. I can create an object graph in code and use that in place of making calls to the database). Also, I'll be using the IoC to perform dependency injection (DI) so I'll "inject" my services into the controllers' contructors as well as the contructors of any other objects that depend on my services. This provides an easy way to create services and use them without having to write the code to instantiate them.

    Let's Begin

    First, let's create a MVC Web application. I'm creating a very simple application for an imaginary Parks & Recreation center so I'll call it "Recreation."

    MVC project creation

    For the type of MVC Web application, I'm going to go with the Basic template. I'm also going to create a unit test project but I'll save the unit tests for another post.

    Basic MVC application

    Once the project is created, add a new controller and name it "HomeController."

    Home Controller

    When the HomeController.cs file opens, right-click in the Index() method and select "Add View..."

    Now run the application (F5) to make sure everything compiles and runs.

    Create a Model/Data Access Layer

    Next, we're going to add a separate class library for our entities/models. Add a new project to the solution and name it "Data."

    Data class library

    Once the project is created, add the assembly references for "System.ComponentModel.DataAnnotations." Then use the NuGet Package Manager to add Entity Framework.

    Entity Framework

    Next create folders named "Context" and "Models" and add the following classes:

    Data Project set-up

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    namespace Data.Models
    {
        public class Facility
        {
            [Key]
            public Int32 Id { get; set; }
    
            [StringLength(100)]
            public String Name { get; set; }
            public Int32 SquareFeet { get; set; }
    
            [Timestamp]
            public Byte[] ConcurrencyToken { get; set; }
    
            public virtual ICollection<Reservation> Reservations { get; set; }
        }
    }
        
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    namespace Data.Models
    {
        public class Guest
        {
            [Key]
            public Int32 Id { get; set; }
    
            [StringLength(100)]
            public String FirstName { get; set; }
            [StringLength(100)]
            public String LastName { get; set; }
    
            [Timestamp]
            public Byte[] ConcurrencyToken { get; set; }
    
            public virtual ICollection<Reservation> Reservations { get; set; }
        }
    }
        
    using System;
    using System.ComponentModel.DataAnnotations;
    
    namespace Data.Models
    {
        public class Reservation
        {
            [Key]
            public Int32 Id { get; set; }
            public DateTime StartDateTime { get; set; }
            public DateTime EndDateTime { get; set; }
    
            [Display(Name = "Facility")]
            public Int32 FacilityId { get; set; }
    
            [Display(Name = "Guest")]
            public Int32 GuestId { get; set; }
    
            [Timestamp]
            public Byte[] ConcurrencyToken { get; set; }
    
            public virtual Facility Facility { get; set; }
            public virtual Guest Guest { get; set; }
        }
    }
        
    using Data.Models;
    using System.Data.Entity;
    using System.Data.Entity.ModelConfiguration.Conventions;
    
    namespace Data.Context
    {
        public class RecreationContext : DbContext
        {
            public RecreationContext()
                : base("name=DefaultConnection")
            {
            }
    
            public DbSet<Facility> Facilities { get; set; }
            public DbSet<Guest> Guests { get; set; }
            public DbSet<Reservation> Reservations { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
                modelBuilder.Entity<Facility>().Property(p => p.ConcurrencyToken).IsConcurrencyToken();
                modelBuilder.Entity<Guest>().Property(p => p.ConcurrencyToken).IsConcurrencyToken();
                modelBuilder.Entity<Reservation>().Property(p => p.ConcurrencyToken).IsConcurrencyToken();
            }
        }
    }
        

    The "RecreationContext" class is like our gateway to the database. We're first going to use it to create the database. The three DbSet properties establish our tables available through the context. The "OnModelCreating" method allows us to set additional characteristics or properties on the tables as well as do things like change the way columns are named or create specific types of relationships between our tables. Here, we're setting up the "ConcurrencyToken" properties in our models to render as timestamp columns in the database. I'm doing this so that we can handle optimistic concurrency (when two or more people retrieve the same record and then attempt to save and overwrite one of the other person's changes).

    To enable Entity Framework Code First, open the Package Manager Console, set the default project to the "Data" project, and type the following:

    Package Manager Console - Enable Migrations

    This will add a new directory to your project, "Migrations," and a new class, "Configuration." The configuration class has a method that will help us seed the new database with some initial values. Replace the Seed method with this:

    protected override void Seed(Data.Context.RecreationContext context)
    {
        var facilities = new List<Facility>()
        {
            new Facility(){
                Name = "West Pavillion",
                SquareFeet = 12020,
                Reservations = new List<Reservation>()
            },
            new Facility(){
                Name = "East Pavillion",
                SquareFeet = 14500,
                Reservations = new List<Reservation>()
            },
            new Facility(){
                Name = "Bounce House",
                SquareFeet = 3000,
                Reservations = new List<Reservation>()
            },
            new Facility(){
                Name = "Botanical Garden",
                SquareFeet = 23123,
                Reservations = new List<Reservation>()
            }
        };
    
        facilities.ForEach(e => context.Facilities.AddOrUpdate(i => i.Name, e));
        context.SaveChanges();
    
        var guests = new List<Guest>()
        {
            new Guest(){
                FirstName = "Adam",
                LastName = "Jones",
                Reservations = new List<Reservation>()
            },
            new Guest(){
                FirstName = "Tiffany",
                LastName = "Bresnev",
                Reservations = new List<Reservation>()
            },
            new Guest(){
                FirstName = "Jackson",
                LastName = "Ackton",
                Reservations = new List<Reservation>()
            }
        };
    
        guests.ForEach(e => context.Guests.AddOrUpdate(i => i.LastName, e));
        context.SaveChanges();
    
        var reservations = new List<Reservation>()
        {
            new Reservation(){
                StartDateTime = new DateTime(2013, 1, 1),
                EndDateTime = new DateTime(2013, 1, 1),
                FacilityId = facilities.Single(p => p.Name == "West Pavillion").Id,
                GuestId = guests.Single(p => p.LastName == "Jones").Id
            },
            new Reservation(){
                StartDateTime = new DateTime(2013, 2, 1),
                EndDateTime = new DateTime(2013, 2, 1),
                FacilityId = facilities.Single(p => p.Name == "Bounce House").Id,
                GuestId = guests.Single(p => p.LastName == "Bresnev").Id
            },new Reservation(){
                StartDateTime = new DateTime(2013, 3, 1),
                EndDateTime = new DateTime(2013, 3, 1),
                FacilityId = facilities.Single(p => p.Name == "Botanical Garden").Id,
                GuestId = guests.Single(p => p.LastName == "Ackton").Id
            }
        };
    
        reservations.ForEach(e => context.Reservations.AddOrUpdate(i => new { i.StartDateTime, i.EndDateTime, i.FacilityId, i.GuestId }, e));
        context.SaveChanges();
    }
        

    When we tell Entity Framework to create the database, the Package Manager Console will look at our start-up project (the MVC project, in this case) and look for the connection string we specified in the RecreationContext class ("DefaultConnection"). I'm going to leave the connection string as the default and create a local database file in the App_Data folder. If you want the database to be created elsewhere, just update the connection string in the Web.config. Next, open the Package Manager Console and type the following:

    Package Manager Console - Initial Create

    This will create a class named "InitialCreate" that has the code necessary for Entity Framework to create the tables in our database. To create the database and generate the tables, type the following in the Package Manager Console:

    Package Manager Console - update-database

    If you open the Server Explorer -> DefaultConnection -> Tables, right-click on the Guest table, and select "Show Table Data," you should see the following:

    Server Explorer

    Let's make sure it works from our MVC application. Replace your HomeController with this:

    using Data.Context;
    using System.Linq;
    using System.Web.Mvc;
    
    namespace Recreation.Controllers
    {
        public class HomeController : Controller
        {
            private RecreationContext db = new RecreationContext();
    
            public ActionResult Index()
            {
                return View(db.Guests.ToList());
            }
    
            protected override void Dispose(bool disposing)
            {
                db.Dispose();
                base.Dispose(disposing);
            }
        }
    }
        

    Then modify your Views -> Home -> Index.cshtml file to look like this:

    @model List<Data.Models.Guest>
    @{
        ViewBag.Title = "Home";
    }
    
    <h2>@ViewBag.Title</h2>
    <ul>
        @foreach (var m in Model)
        {
            <li>@m.FirstName @m.LastName</li>
        }
    </ul>
        

    Run the application (F5) and you should see the three names we seeded to the database when it was created.

    Using the Unity IoC Container to Inject Dependencies in Your Controller

    First, install the Unity bootstrapper for ASP.NET MVC.

    NuGet Unity Bootstrapper

    This will also add the Unity NuGet package. The bootstrapper adds the necessary files in the MVC project's App_Start directory to initialize Unity and set the dependencies (the things you want to inject into other classes or methods). If you look in App_Start, you'll see two new files: UnityConfig.cs and UnityMvcActivator.cs. UnityMvcActivator uses WebActivatorEx to call the class's Start() method during application start. Of particular interest in the Start() method are the following lines:

    // TODO: Uncomment if you want to use PerRequestLifetimeManager
    // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
        

    Unity has what's called "lifetime managers" that manages how long any given object stays instantiated (alive). The The PerRequestLifetimeManager calls Dispose() on any object that makes use of the manager at the end of the HTTP request. We want to do this for our ObjectContext (RecreationContext) object so that it doesn't stay alive on the server, available for other requests. Make sure you uncomment the line so that we can safely dispose of any resources that implement IDisposable.

    The reason for my aforementiond head-banging was that I installed "Unity" and "Unity.MVC4" NuGet packages instead of the "Unity bootstrapper for ASP.NET MVC" package. The PerRequestLifetimeManager and UnityPerRequestHttpModule are only available in the bootstrapper package. I attempted to build several per-request lifetime managers but could never get them to call Dispose() on my managed services. It was ultimately the HttpModule that I was missing.

    Using the Inversion of Control, Repository, and Unit Of Work Patterns

    The Inversion of Control (IoC) pattern is all about resolving one type to another type. This resolution could be based on inheritance but most often you'll see it based on an interface. With this pattern, you develop against an interface and let the IoC container resolve it to a concrete implementation of that interface. You could have any number of implementations, it's up to the IoC container to create one for you. One of the ways it can do this is through Dependency Injection (DI). What you have is a consumer component (e.g. a MVC controller) that declares a dependency (or multiple dependencies) that it needs to get its job done. (Most commonly, you'll see this done through the constructor but some IoC frameworks allow you to inject through properties.) The IoC container creates an instance of a class that implements that given interface at runtime and "injects" it into that component. This pattern is somewhat like the Factory method pattern except that IoC relies on an external framework to operate (e.g. Unity, Windsor, Ninject, StructureMap). So IoC is really more of an architectural pattern as opposed to a design pattern.

    What we want now is an interface we can program against to get data from the Entity Framework ObjectContext (RecreationContext) we set up earlier. The interface should be generic enough that we can swap it out for another data access framework if we want but still robust enough to give us what we need to get things done in our controllers. The Repository pattern is ideal for this situation:

    A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes.

    So the repository is responsible for persisting our objects in memory but what about when it comes time to save changes to the collection(s) back to the database? That's where the Unit of Work pattern comes into play:

    A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.

    Perfect!

    So that we can reuse our Repository and UnitOfWork classes, lets create a separate class library and call it something like "Core." Note that I'm placing it in the Projects directory and not the Recreation directory. That way I can easily reference the assembly when creating other projects. A "core" assembly is a great place to store commonly used code like extension methods, helper methods, and anything else you may want to use from project-to-project. (Ideally, you would place the IRepository and IUnitOfWork interfaces - along with their dependencies - in a "core" assembly and then create another assembly with an ORM-specific implementation but I'm going to combine them at this time for the sake of simplicity.)

    Core Class Library

    After you create the class library, install Entity Framework from the NuGet Package Manager then add these interfaces, classes, and enum:

    namespace Core
    {
        public enum EntityStatus : int
        {
            Added,
            Deleted,
            Detached,
            Modified,
            Unchanged
        }
    }
        
    using System;
    using System.Runtime.Serialization;
    
    namespace Core
    {
        public class ConcurrencyException : SystemException
        {
            public ConcurrencyException()
                : base()
            {
            }
    
            public ConcurrencyException(String message)
                : base(message)
            {
            }
    
            public ConcurrencyException(String message, Exception innerException)
                : base(message, innerException)
            {
            }
    
            public ConcurrencyException(SerializationInfo info, StreamingContext context)
                : base(info, context)
            {
            }
        }
    }
        
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    
    namespace Core
    {
        public interface IRepository<T> : IDisposable where T : class
        {
            IQueryable<T> GetQueryable();
            IEnumerable<T> GetAll();
            IEnumerable<T> Find(Expression<Func<T, Boolean>> where);
            T Single(Expression<Func<T, Boolean>> where);
            T First(Expression<Func<T, Boolean>> where);
            void Delete(T entity);
            void Add(T entity);
            void Attach(T entity);
            void Attach(T entity, EntityStatus status);
        }
    }
        
    using System;
    
    namespace Core
    {
        public interface IUnitOfWork : IDisposable
        {
            void SaveChanges();
        }
    }
        
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity.Infrastructure;
    using System.Data.Objects;
    using System.Linq;
    using System.Linq.Expressions;
    
    namespace Core
    {
        public class Repository<T> : IRepository<T> where T : class
        {
            private readonly IObjectContextAdapter _ObjectContextAdapter;
            IObjectSet<T> _ObjectSet;
    
            public Repository(IObjectContextAdapter objectContextAdapter)
            {
                _ObjectContextAdapter = objectContextAdapter;
                _ObjectSet = objectContextAdapter.ObjectContext.CreateObjectSet<T>();
            }
    
            public IQueryable<T> GetQueryable()
            {
                return _ObjectSet;
            }
    
            public IEnumerable<T> GetAll()
            {
                return _ObjectSet.ToList();
            }
    
            public IEnumerable<T> Find(Expression<Func<T, Boolean>> where)
            {
                return _ObjectSet.Where(where);
            }
    
            public T Single(Expression<Func<T, Boolean>> where)
            {
                return _ObjectSet.Single(where);
            }
    
            public T First(Expression<Func<T, Boolean>> where)
            {
                return _ObjectSet.First(where);
            }
    
            public void Delete(T entity)
            {
                _ObjectSet.DeleteObject(entity);
            }
    
            public void Add(T entity)
            {
                _ObjectSet.AddObject(entity);
            }
    
            public void Attach(T entity)
            {
                Attach(entity, EntityStatus.Unchanged);
            }
    
            public void Attach(T entity, EntityStatus status)
            {
                _ObjectSet.Attach(entity);
                _ObjectContextAdapter.ObjectContext.ObjectStateManager.ChangeObjectState(entity, GetEntityState(status));
            }
    
            public void Dispose()
            {
                if (_ObjectContextAdapter != null)
                    _ObjectContextAdapter.ObjectContext.Dispose();
    
                GC.SuppressFinalize(this);
            }
    
            private EntityState GetEntityState(EntityStatus status)
            {
                switch (status)
                {
                    case EntityStatus.Added:
                        return EntityState.Added;
                    case EntityStatus.Deleted:
                        return EntityState.Deleted;
                    case EntityStatus.Detached:
                        return EntityState.Detached;
                    case EntityStatus.Modified:
                        return EntityState.Modified;
                    default:
                        return EntityState.Unchanged;
                }
            }
        }
    }
        
    using System;
    using System.Data;
    using System.Data.Entity.Infrastructure;
    
    namespace Core
    {
        public class UnitOfWork : IUnitOfWork
        {
            private readonly IObjectContextAdapter _ObjectContextAdapter;
    
            public UnitOfWork(IObjectContextAdapter objectContextAdapter)
            {
                _ObjectContextAdapter = objectContextAdapter;
            }
    
            public void SaveChanges()
            {
                try
                {
                    _ObjectContextAdapter.ObjectContext.SaveChanges();
                }
                catch (OptimisticConcurrencyException oce)
                {
                    throw new ConcurrencyException(oce.Message, oce.InnerException);
                }
                catch (DataException)
                {
                    throw;
                }
            }
    
            public void Dispose()
            {
                if (_ObjectContextAdapter != null)
                    _ObjectContextAdapter.ObjectContext.Dispose();
    
                GC.SuppressFinalize(this);
            }
        }
    }
        

    To implement the repository and unit of work into our MVC application, update the UnityConfig.cs file as follows:

    using Core;
    using Data.Context;
    using Microsoft.Practices.Unity;
    using System;
    using System.Data.Entity.Infrastructure;
    
    namespace Recreation.App_Start
    {
        /// <summary>
        /// Specifies the Unity configuration for the main container.
        /// </summary>
        public class UnityConfig
        {
            #region Unity Container
            private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
            {
                var container = new UnityContainer();
                RegisterTypes(container);
                return container;
            });
    
            /// <summary>
            /// Gets the configured Unity container.
            /// </summary>
            public static IUnityContainer GetConfiguredContainer()
            {
                return container.Value;
            }
            #endregion
    
            /// <summary>Registers the type mappings with the Unity container.</summary>
            /// <param name="container">The unity container to configure.</param>
            /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to 
            /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
            public static void RegisterTypes(IUnityContainer container)
            {
                // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
                // container.LoadConfiguration();
    
                // TODO: Register your types here
                container.RegisterType<IObjectContextAdapter, RecreationContext>(new PerRequestLifetimeManager());
                container.RegisterType(typeof(IRepository<>), typeof(Repository<>));
                container.RegisterType<IUnitOfWork, UnitOfWork>();
            }
        }
    }
        

    What we're doing here is registering the interfaces and associating them with a concrete type in the RegisterTypes() method. Throughout the MVC application, we'll program against the interface but at runtime, Unity will inject a concrete instance of the interface.

    In the above code, the RecreationContext is instantiated per-request thanks to the PerRequestLifetimeManager. Here's the cool part: both Repository and UnitOfWork have constructors that accept IObjectContextAdapter. When the concrete implementations are instantiated, Unity injects the RecreationContext into them and then they get injected into the controller (see below). Both the Repository and the UnitOfWork then share the same context per request so that anything that happens in the Repository gets reflected in the UnitOfWork. How freaking cool is that?!

    Now we can update our HomeController to look like this:

    using Core;
    using Data.Models;
    using System.Web.Mvc;
    
    namespace Recreation.Controllers
    {
        public class HomeController : Controller
        {
            IRepository<Guest> _GuestRepository;
    
            public HomeController(IRepository<Guest> guestRepository)
            {
                _GuestRepository = guestRepository;
            }
    
            public ActionResult Index()
            {
                return View(_GuestRepository.GetAll());
            }
    
            protected override void Dispose(bool disposing)
            {
                _GuestRepository.Dispose();
                base.Dispose(disposing);
            }
        }
    }
        

    Now run the application (F5) and verify that the save values from the database are displayed in the view.

    When the controller is created, Unity inspects its constructor and compares the types in the signature with the registered types in its container. In this case, it found a generic IRepository<> interface and passed in an instance of the Repository<> class. By making the IRepository interface and Repository concrete implementation generic, we can create repositories for any number of Entity objects. You can inject as many items into a constructor as you want, too. Just add them to the constructor's method signature [e.g. public HomeController(IRepository<Guest> guestRepository, IRepository<Facility> facilityRepository, IRepository<Reservation> reservationRepository) and so on...]

    When you make changes through the repository, you're actually making changes to the Entities in the underlying ObjectContext. When it comes time to commit those changes back to the database, the Unit of Work we created earlier has that responsibility. Update your HomeController to this:

    using Core;
    using Data.Models;
    using System;
    using System.Web.Mvc;
    
    namespace Recreation.Controllers
    {
        public class HomeController : Controller
        {
            IRepository<Guest> _GuestRepository;
            IUnitOfWork _UnitOfWork;
    
            public HomeController(IRepository<Guest> guestRepository, IUnitOfWork unitOfWork)
            {
                _GuestRepository = guestRepository;
                _UnitOfWork = unitOfWork;
            }
    
            public ActionResult Index()
            {
                return View(_GuestRepository.GetAll());
            }
    
            public ActionResult Edit()
            {
                return View(_GuestRepository.First(g => g.LastName == "Bresnev"));
            }
    
            [HttpPost]
            public ActionResult Edit(Guest guest)
            {
                _GuestRepository.Attach(guest, EntityStatus.Modified);
    
                if (ModelState.IsValid)
                {
                    try
                    {
                        _UnitOfWork.SaveChanges();
                    }
                    catch (ConcurrencyException)
                    {
                        ModelState.AddModelError(String.Empty, "The record you attempted to edit was modified by another user after you got the original value. Your edit operation was canceled. If you still want to edit this record, save it again.");
                    }
                    catch (Exception)
                    {
                        ModelState.AddModelError(String.Empty, "Unable to save changes. Please try again.");
                    }
                }
    
                return View(guest);
            }
    
            protected override void Dispose(bool disposing)
            {
                _GuestRepository.Dispose();
                _UnitOfWork.Dispose();
                base.Dispose(disposing);
            }
        }
    }
        

    Right-click within the Edit() method and add a View. Change the Edit.cshtml view to look like this:

    @model Data.Models.Guest
    @{
        ViewBag.Title = "Edit";
    }
    
    <h2>@ViewBag.Title</h2>
    <ul>
        <li>@Model.FirstName @Model.LastName</li>
    </ul>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
    
        @Html.TextBoxFor(m => m.FirstName);
        
        @Html.HiddenFor(m => m.Id)
        @Html.HiddenFor(m => m.LastName)
        @Html.HiddenFor(m => m.ConcurrencyToken)
        <input type="submit" value="Change First Name" />
    }
        

    I realize this is a pretty lame example but I just wanted to get the idea across.

    The reason for creating my own ConcurrencyException and managing my own Entity state/status is that I didn't want to create any dependencies on Entity Framework in the interfaces. I'm not sure about other ORM's but I can imagine that there are ways on others to manage concurrency exceptions or the status change of an object. The point, though, is to make an interface that's as neutral as possible to a concrete implementation so that you can change the concrete implementation without having to change the interface and the code depending on that interface.

    Please let me know if you have any suggestions on how to make this better!

    You can get the code here.

  3. Handling Inheritance Using Table-Per-Type in Entity Framework Code First

    There are a few ways to handle persisting inheritance with Entity Framework 5 Code First. Table-Per-Hierarchy and Table-Per-Type are the most common. TPH seems to be the most prevalent but I'm not a huge fan. With TPH, only one table is created to handle the parent type and it's child types.

    For example, suppose you had a class named "Person" and two inherited classes named "Instructor" and "Student". "Person" has two properties: "FirstName" and "LastName." "Instructor" as a property for "HireDate." "Student" has a property for "EnrollmentDate." When Entity Framework creates the database for this model, by default it creates a single table with columns for all of the class properties. "HireDate" and "EnrollmentDate" are nullable such that "Instructor" records would have a value for "HireDate" but "EnrollmentDate" would be null whereas "Student" records would have a value for "EnrollmentDate" but "HireDate" would be null. To distinguish among the different sub-types, there's a "Discriminator" column added to the table that holds the name of the sub-type (e.g. "Instructor" and "Student"). The "Discriminator" column denormalizes the data and would likely irritate any DBA's in your organization.

    When you set up your classes to use Table-Per-Type, three tables are created: "Person," "Instructor," and "Student" with one-to-one relationships. You avoid the denormalization but, supposedly, there's a performance cost on the Entity Framework side because you have to join the tables when you query them. Personally, I'd rather avoid the denormalization - especially for tables that are expected to grow to any great number of rows.

    Here are the classes:

    public abstract class Person
    {
        [Key]
        public Int32 Id { get; set; }
        public String FirstName { get; set; }
        public String LastName { get; set; }
    }
    
    public class Instructor : Person
    {
        public DateTime HireDate { get; set; }
    }
    
    public class Student : Person
    {
        public DateTime EnrollmentDate { get; set; }
    }
        

    I prefer to use the Fluent API to specify how the tables are created as opposed to using attributes in the POCO classes. To get EF to create the separate tables, use the .ToTable(tableName) method:

    public class UniversityContext : DbContext
    {
        public DbSet<Person> People { set; get; }
        public DbSet<Instructor> Instructors { set; get; }
        public DbSet<Student> Students { set; get; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    
            modelBuilder.Entity<Instructor>().ToTable("Instructor");
            modelBuilder.Entity<Student>().ToTable("Student");
        }
    }
        
  4. Accidental Learning (Redux)

    I'm catching up on Entity Framework so I'm reading Julie Lerman's excellent books: "Programming Entity Framework," "DbContext," and "Programming Entity Framework: Code First." For grins, I Googled her using Bing and found this gem on her blog.

    It's also interested me to consider how this process, repeated over the years, has resulted in my having a quiver filled with a slew of little bits of very useful, somewhat scattered, information. This is very different than learning a big topic, like testing or Entity Framework. However they are a starting point at which I can leverage the tool and make it work for me.

    I mentioned in my last post that our brains are great for long-term storage for things we do frequently but no-so-great for things we've only done once or twice. Like Julie, I have tons of scattered information about a wide variety of topics - just enough to make me dangerous - and thousands of lines of code I've written over the years that serve as an excellent resource when I come across a new problem that's similar to one I've already solved. I completely understand what she means by these pieces of information and little snippets of things we've done in the past being leveragable tools for getting things done.

    My recent string of interviews has been a really defeating experience. There's nothing quite like sitting in front of someone who seemingly holds my career in their hands as they pound me with questions on the inner workings of SQL Server or ask me to diagram a game of five card draw on a whiteboard using every known design pattern. Index tuning and UML diagramming are things I've done in the past but were done infrequently and sporadically. Recalling them (or, rather, in the interviews I've had recently, not recalling them) has been challenging and has really made me question a 15-year career in programming.

    On the other hand, my recent string of interviews has also been a really great learning experience. I've been in somewhat of a vacuum the past 12 years by working in one industry/market and on very small development teams extending a single product. As a result, I've missed out on some of the methodologies and technologies that have gained favor in the past few years - namely Test-Driven Development (TDD) and Entity Framework. Now that I know I have some deficiencies, it's time to get to work and fill those knowledge gaps.

    Reading Julie's post made me realize that I'm not the only one that has learned a wide variety of things - if even accidentally - and has become a "jack of all trades, master of none" developer (though she has written three books so I'd consider her a master at Entity Framework). It's nice to know I'm in good company.

  5. I'm smart and I get things done.

    I've been interviewing for a new job over the past several weeks. In the past, I've gotten jobs through contacts and word-of-mouth but now that I'm branching out to other industries, I'm finding the job search to be really tedious.

    "That's the trouble with the world today. No one takes the time to do a really sinister interrogation anymore. It's a lost art."
    ~ James Bond, Goldeneye

    Trivial Pursuits

    Over the past several weeks, I've been somewhat perplexed about whether I'm being interviewed for a job or participating in an episode of "Jeopardy!". Five of the seven interviews I had last week were solely trivia tests. "What is the MVC pattern?," "What properties would you set when using jQuery to make an AJAX call?," "What is ACID in the context of databases?," and "What is the difference between a primary key and a unique constraint?" were just a few of the questions I was asked. These questions are great for a college pop quiz but do little to determine someone's experience, intelligence, or talent.

    For example, at one of my first tech jobs, the CTO hired someone that could answer absolutely every technical trivia question he was asked. The guy was a machine. Without blinking - without even waiting for the interviewer to finish the question - he spat out the answer with textbook accuracy. "This candidate is amazing!," we were told. "You're really going to learn a lot from him." He was fired a few months later because of a total lack of performance on the job. He couldn't write a line of code to save his life. (After the first week, I seriously wanted to put that metaphor to the test, too.)

    Interviews disguised as trivia contests give me some insight as to the type of company and employees with whom I would be working. If the interviewer doesn't want to get to know me and discover what makes me tick, then I probably don't want to work for them. I'm at least going to be wary going into the next phase of the interview process or when it comes time to accept an offer.

    "Reality is merely an illusion, albeit a very persistent one."
    ~ Albert Einstein

    I've only had one interview so far where I was asked to write some code. I was initially excited when it was explained that the test had three parts: SQL, C#, and UI (HTML5 and jQuery). I anticipated that I would be given a business problem to solve and that I would be designing a simple database schema, writing some data-retrieval code and some business logic, and displaying the data in a Web application. These are simple tasks that I perform every day and would be a great way to show how I organize projects and solve common problems.

    If only...

    For the SQL portion, I was asked to write two simple queries based on a schema diagram they provided. I nailed both of those without any problem so I was off to a good start!

    For the C# part of the test, I was asked to examine code similar to this:

    public class Program
    {
        static void Main(String[] args)
        {
            Int32[][] array = { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9 } };
            Console.WriteLine(GetValue(array));
            Console.Read();
        }
    
        private static Int32 GetValue(Int32[][] array)
        {
            return ProcessValue(array, array.Rank, array.Length - 1, 0, -1) - ProcessValue(array, 0, 1, array.Length - 1, 2);
        }
    
        private static Int32 ProcessValue(Int32[][] array, Int32 x, Int32 y, Int32 w, Int32 z)
        {
            return array[y - x][w - z];
        }
    }
        

    Without running the program, I was asked to solve the output. "This is to see if your brain can serve as a compiler," I was told. Thankfully I was given a piece of paper and a pen. I spent an equal amount of time working on the problem as I did debating in my head whether I should politely excuse myself walk out. Ultimately, I didn't get the correct answer; I was off by 1. Based on that, I failed the interview and didn't get the job. Thankfully! If my days there were to be spent "compiling" code in my head and solving inconsequential puzzles, I would have gone insane and quit within a week.

    To make matters worse, this particular interviewer stood two feet off my left shoulder and watched every keystroke. I had to wonder if he was going to do that once I was hired. If that isn't their normal work environment, then why test me in such an environment? If a test isn't based on reality, then why administer the test?

    Build an atom bomb to prove you can make a firecracker.

    I have no problem with being asked to write a little code to show that I have at least some basic understanding of programming. It's important to make sure a candidate knows the fundamentals of looping and conditional logic, for example. One of my favorites is the "FizzBuzz" problem:

    Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

    A problem like this is simple, can be solved in at most 10 to 15 minutes and is a good indicator that the candidate isn't faking their understanding of basic programming.

    Incidentally, the result could look something like this:

    for (Int32 i = 1; i <= 100; i++)
    {
        if (i % 3 == 0 && i % 5 == 0)
            Console.WriteLine("FizzBuzz");
        else if (i % 3 == 0)
            Console.WriteLine("Fizz");
        else if (i % 5 == 0)
            Console.WriteLine("Buzz");
        else
            Console.WriteLine(i);
    }
        

    Anything more complicated than that is superfluous. Asking a programmer to write a complex application for you during an interview is like asking an electrician to build an electrical grid for you before they replace a lightbulb.

    We're looking for a developer, just not a resourceful developer.

    How many developers do you know that have never had to rely on a resource to solve a problem? None, you say? Then why would you limit a developer you're testing by excluding the use of resources? Every single technical test I've taken during an interview disallowed the use of any resource during the test. Here's a thought: why not blindfold me and and tie my hands behind my back, too?

    The human brain is incredible in the way it can store vast amounts of information. However, it is limited. For repetitive things, our brains are awesome at long-term storage. For things we've only done once or twice? Not so much. For those things, I rely extensively on a much more reliable storage mechanism: hard drives. My laptop is filled with code samples I've written over the years. When I encounter a complex problem that I've solved before or a problem similar to one I've solved before, I reach for that code; I adapt it to the current problem. If I had to struggle to reinvent the wheel for each and every problem I encountered, I'd rarely meet any deadline.

    There's another resource I use which, for whatever reason, interviewers always want to disallow: the Internet. This makes no sense whatsoever. Searching the Internet for the solution to a problem is, in many ways, an art form and it's a skill that every developer must have in their arsenal. What a developer does to find the solution to a problem should be part of the test!

    You should want developers who are resourceful. You should want developers who can learn. If you don't, then I'm not a good fit for your organization.

    The Pragmatic Passionate Programmer

    The two interviews I had last week that interested me asked questions like:

    • What was the most interesting part of the last project on which you worked?
    • What is the most recent technology you've learned, why did you want to learn it, and how did you learn it?
    • Why did you choose to use technology X over technology Y in your last project?

    These questions explore the two most important traits of a good programmer: the ability to learn and a passion for the craft of programming.

    That last question, though, really bothered me at the time. You see, I explained to the interviewer that I was the chief architect and lead developer on my most recent project. The project was your standard 3-tier architecture - SQL Server dababase, business layer/ORM, and a Silverlight front end. The ORM I chose to use was my own which is based on Martin Fowler's excellent "Patterns of Enterprise Application Architecture." It has been continually developed, enhanced, and maintained over the past 12 years and has proven to be very successful in every project where I've used it. The interviewer questioned why I used my own ORM instead of a commercially-produced ORM like Entity Framework or an open-source ORM like NHibernate. I explained that I had evaluated those ORM's and had to consider that the team I was tasked to lead had little OOP experience and that my ORM was very direct and simple to use. "Well, I think that was a mistake because if you use a commercial product or something that's community-driven then you get the benefit of a large group's expertise as opposed to just one person and you also have the benefit of regular updates and enhancements from the community," she said. We hotly debated the pro's and con's of my decision and, in the end, agreed to disagree. (Toward the end of the interview, she actually apologized for being so openly hostile toward me.) At the time, I was irritated that she was so quick to dismiss 12 years of hard work without ever having seen it. Now, however (though I don't think it was intentional on her part), I see that it was actually a really good interview technique. She was able to get me to show passion for my work, my love for programming, and an ability and willingness to defend my decisions in spite of the desire to please her just to get the job.

    Would you hire a chef without first tasting his food?
    Then why would you hire a programmer without first having seen his code?

    I have yet to be interviewed for a position where the interviewer has asked to see a sample of my work. This is really disappointing. When I was a hiring manager, I would ask the candidates to bring their laptop (or at least print out some code) so that I could see something that they've written of which they're particularly proud. Once it was in front of us, I would ask what was the business problem that was solved. I would then ask for them to walk me through the code. I could usually get a good sense of the type of developer I was interviewing. I could see the way they formatted code - did they care enough to make it pretty; did they name classes, methods, and variables in such a way that the code was self-documenting; did they organize the project in a way that others could easily pick up the project and work on it, etc. I could get a sense of their thought processes - did they approach the problem in a logical manner, did they think in an object-oriented or procedural manner, etc. Most importantly, though, I could get a sense of their passion for solving the problem. If the candidate became animated and excited about what they were explaining to me, that candidate was a contender.

    Smart and Productive? You mean you can have both?

    Joel Spolsky has two criteria for hiring a good developer: you're looking for people who 1.) are smart and 2.) get things done.

    People who are Smart but don’t Get Things Done often have PhDs and work in big companies where nobody listens to them because they are completely impractical. They would rather mull over something academic about a problem rather than ship on time. These kind of people can be identified because they love to point out the theoretical similarity between two widely divergent concepts. For example, they will say, “Spreadsheets are really just a special case of programming language,” and then go off for a week and write a thrilling, brilliant whitepaper about the theoretical computational linguistic attributes of a spreadsheet as a programming language. Smart, but not useful. The other way to identify these people is that they have a tendency to show up at your office, coffee mug in hand, and try to start a long conversation about the relative merits of Java introspection vs. COM type libraries, on the day you are trying to ship a beta.

    People who Get Things Done but are not Smart will do stupid things, seemingly without thinking about them, and somebody else will have to come clean up their mess later. This makes them net liabilities to the company because not only do they fail to contribute, but they soak up good people’s time. They are the kind of people who decide to refactor your core algorithms to use the Visitor Pattern, which they just read about the night before, and completely misunderstood, and instead of simple loops adding up items in an array you’ve got an AdderVistior class (yes, it’s spelled wrong) and a VisitationArrangingOfficer singleton and none of your code works any more.

    Conclusion

    So if you're thinking of interviewing me for a position at your company, please take these ideas into consideration. Please ask me questions through which I can demonstrate that I'm smart and that I can get things done. If you only throw "Aha!" questions at me or ask me to solve trivial brainteasers, don't be surprised if I politely excuse myself and never return. You see, I'm interviewing you just as hard as - if not harder than - you're interviewing me. You're looking for a good employee but I'm looking for a good employer.