Dec 26 2011

When Encryption Is Part Of Your Domain

Category: MiscMatt @ 16:25

We typically think of encryption as a cross-cutting concern or as a separate utility service that our applications use, not as something that’s an integral part of our application domain.  That way of thinking doesn’t always hold though.  In this short post, I’ll show you how I recently implemented support for encryption as a first-class citizen of my domain model. 

The Domain

Almost every application contains some element that needs to be encrypted or hashed (a user’s credentials, perhaps?).  In the past, I’ve never bothered encapsulating the encrypted value as its own separate data type.  I’ll still encapsulate the logic for encrypting or hashing in the domain, but I typically place that logic in the owning entity.  Here’s a User object from RageFeed as an example:

public class User
{
    public virtual Guid Id { get; set; }

    public virtual string Username { get; set; }

    public virtual string Email { get; set; }

    public virtual string PasswordSalt { get; set; }

    public virtual string PasswordHash { get; set; }

    ...snip...

    public virtual void SetPassword(string password)
    {
        GenerateNewSalt();

        PasswordHash = HashPassword(password);
    }

    public virtual bool IsThisTheUsersPassword(string password)
    {
        var hash = HashPassword(password);

        return hash == PasswordHash;
    }

    private string HashPassword(string password)
    {
        ...snip...
    }

    private void GenerateNewSalt()
    {
        ...snip...
    }

    ...snip...
}

There’s quite a bit of logic related to securely storing the user’s password in this redacted snippet.  While it’s fairly easy to test, it does make for a slightly less-cohesive domain model since there are now true business concerns mixed in with encryption concerns.  Since it was really only this one entity and applied only to the credentials, I decided at the time to leave the code in the User object instead of refactoring it to somewhere else. 

Encrypted Members as a First Class Citizen

On a recent application though, I found that I had several members that all needed to be encrypted.  I decided I would encapsulate the encrypted members as first-class data types instead of rolling the encryption responsibility into the owning entity.  The difference is subtle, but it greatly changes where behavior lives within the domain.  The entities with encrypted members become simpler and more cohesive since they no longer contain encryption-related logic.  That logic is now encapsulated separately from the owning entity and is far easier to reuse throughout the domain.

public class AccountDetails
{
    ...snip...

    public virtual EncryptedString ReallySecretNumber { get; private set; }
    
    public virtual EncryptedString AnotherReallySecretNumber { get; private set; }
    
    ...snip...
}

The actual data type doesn’t do much directly: 

public class EncryptedString
{
    public virtual string EncryptedValue { get; set; }

    public virtual string CertificateName { get; set; }

    public virtual string Key { get; set; }

    protected EncryptedString()
    {

    }

    public static EncryptedString Create(string value, IEncryptData encrypter)
    {
        var encryptionResult = encrypter.Encrypt(value);

        return new EncryptedString
        {
            EncryptedValue = encryptionResult.EncryptedText,
            CertificateName = encryptionResult.CertificateName,
            Key = encryptionResult.Key
        };
    }

    public virtual string GetDecryptedValue(IEncryptData encrypter)
    {
        return encrypter.Decrypt(EncryptedValue, CertificateName, Key);
    }
}

Instead, it depends on a separate service, IEncryptData, to provide the low-level encryption API it requires.  This keeps the domain decoupled from the low-level methods, making it easier to test, extend, and maintain in the future.

Which is Better?

As always, the answer is “it depends.”  The approach I took with RageFeed and Fail Tracker, where I embedded the logic within the owning entity, has never caused me issues.  However, I chose to go a different route as soon as I had multiple members that required encryption.  That feels like the right approach in this case. 

Tags:

Oct 8 2011

My Rambling Thoughts on Scrum

Category: MiscMatt @ 02:17

I’ve spent the last year working at a company that embraced Agile from the top-down.  I’ve been on a Scrum team as it transitioned from semi-chaos to self-organizing and back to complete-chaos.  I’ve seen Scrum at its best and at its worst.  During this year, I’ve made a few observations on Scrum, its strengths, and its weaknesses.  Read on, ye readers, to find out why I think Scrum fails.

More...

Tags:

Sep 23 2011

What’s in your Definition of Done?

Category: Misc | Best PracticesMatt @ 03:38

Every team, whether you are practicing agile or not, regardless of platform or language, should really have some Definition of Done.  What does it mean for a story/feature/defect/whatever to be “done?”  What things have to happen to achieve “done” status?  Defining these things will help with estimating effort, and it may also help increase the quality of your product.  Here are a few of the things I look for in a Definition of Done.

More...

Tags:

Sep 9 2011

What questions should you ask if you are the interviewee?

Category: MiscMatt @ 07:44

Here’s another one for the non-.NET category.  I’ve been involved in both sides of the interview process recently.  I previously outlined the types of questions I ask if I’m in the interviewer seat, but what about about when I’m the interviewee?  Asking the right questions as an interviewee is just as important (if not more important) than asking the right questions as the interviewer.  The position you are interviewing for is going to play a major role in your life.  You need to find out now if it isn’t a good fit for you.  Here are some of the questions I like to ask.

More...

Tags:

Jun 16 2011

Interview Questions

Category: MiscMatt @ 12:15

So we’re hiring another senior developer for our team at my day job, and I’ve spent a fair amount of time in the last week brushing up my list of questions (and coding exercises).  There are tons of posts strewn across the web of developer interview questions, but I thought I’d add my own thoughts to the mix.  Here are the questions you’re likely to encounter should you interview with me.  

More...

Tags:

Jun 4 2011

CodeStock 2011 Was A Success!

Category: MiscMatt @ 13:12

Well, another CodeStock has come and gone.  This year was great.  I’m mentally and physically exhausted (three straight hours of talking wears you out!), but it was well-worth it.  I met some cool people, attended some great sessions, and had a terrific audience for both of my talks.  I’ll be posting more content in the coming weeks spinning out of the conference, and the recordings should be available in the next couple of weeks (I hope).  In the mean time, feel free to hop on over to my github page to check out Fail Tracker, or download the presentations below if you just want to see the slides.  Thanks again to everyone that attended and to everyone that presented!  CodeStock keeps getting better and better, and I’m already looking forward to next year!

Tags:

Mar 30 2011

Come See Me At CodeStock 2011!

Category: MiscMatt @ 12:10

The lineup for CodeStock has officially been announced, and this looks to be the best CodeStock yet.  As usual, there’s going to be a great group of speakers and sessions.  I will be presenting two sessions at CodeStock this year.  This first, Build Your Own Application Framework with ASP.NET MVC 3, will be a two hour session covering some of the best practices I’ve picked up over the years while building MVC applications.  In the second session, Test-Driven Development Using SpecsFor, I will show you everything from the basics of unit testing to the art (and benefit) of doing TDD.  CodeStock is a great value (and no, I’m not being paid to say that).  If you’re anywhere near Knoxville, Tennessee, you really should come check it out.  $60 for two days of great speakers and sessions, a t-shirt, and buffet-style lunch? You really can’t beat that!

Tags:

Feb 23 2011

Vote For Me At CodeStock 2011!

Category: MiscMatt @ 05:00

CodeStock is a great developer-driven event that’s hosted in Knoxville, TN.  It’s a terrific bargain: two days of learning and hanging out with other great devs, plus food and drinks, all for a price that’s significantly less than other similar events.  As is the case every year, attendees decide which sessions will be part of CodeStock.  I’ve submitted three sessions this year, and I want your votes!

SOLID – What Is It Good For? Absolutely… Nothing!?!?!

“Blasphemy! How dare you disparage the sacred acronym of SOLID?!?!!” Relax, I agree! SOLID is great. Paying attention to these principles will often lead you right and only seldom lead you wrong. But there’s a deeper truth underneath the SOLID principles. It’s about a topic you were most likely educated about (poorly) in your software engineering courses. Coupling. Coupling, that maintainability-killing monster that your professors vaguely warned you about, is what SOLID helps you avoid. SOLID is all about reducing coupling. In this session, you’ll get a quick introduction to SOLID, learn all about cohesion and coupling, and see useful statistics for assessing the two. Once you better understand what coupling is and how SOLID helps you avoid it, you will see that the principles are useful reminders and guides. You will find yourself far better equipped than before to evaluate design alternatives and minimize coupling than you were with SOLID alone.

Test-Driven Development Using SpecsFor

Are you one of those people that just doesn’t “get” TDD? Have you tried it, but found that it only hindered you instead of helped? If so, this session is for you. In 60 minutes, we’ll go from “Neophyte Tester” to “Lord of the Tests” using NUnit, Moq, StructureMap, and SpecsFor. If you like PowerPoint or dream of never-ending bullet-point lists, this session is not for you. However, if you find lambda expressions exciting, if you are fascinated by Resharper wizardry, and if you prefer a more code-oriented discussion, this just might be the session you’re looking for.

Build Your Own Application Framework with ASP.NET MVC 3

You’ve finally done it. You sold it to your fellow developers. You fought with your boss and finally won his buy-in. You’re finally making the switch to ASP.NET MVC. You promised your boss more features, less bugs, and faster turn-around. But there’s a surprise waiting for you. ASP.NET MVC is much less a “framework” than a set of building blocks that you can use to create an actual framework. If you don’t invest in building up a proper framework for your application, you will encounter maintenance woes that make even WebForms look tame. In this session, I’ll show you how to take full advantage of what ASP.NET MVC brings to the table while creating a robust, extensible application framework. You’ll see how to push common concerns into your framework and away from your day-to-day development activities. Topics we’ll cover include establishing conventions for generating your UI, how to leverage newdependency-injection features of MVC 3, separating concerns with an application bus, and we’ll even cover some jQuery black magic.

So what are you waiting for?  Go register and vote (for me!) right now.  Early bird registration is only $60 and includes two days of awesome content plus food and a shirt. You really can’t beat that!

Tags:

Feb 19 2011

Friday Programming Challenge–The Answer

Category: MiscMatt @ 01:00

Yesterday I presented a problem that I struggle with for several hours: given a generic Func<T,object> created by a fluent DSL, how can I call a method that only accepts a non-generic Func<object,object>?  The answer is actually quite simple.

Here’s the relevant non-compiling code from yesterday:

internal interface ISerializationConfig
{
    ...
    void SerializePropertyAsElementUsing(Type target, 
             PropertyInfo property, 
             string elementName, 
             Func<object, object> converter);
}


... 

ITypeSerializationSpec<T> IInitialPropertySerializationSpec<T>.Using(Func<T, object> selector)
{
    //_config is of type ISerializationConfig. 
    _config.SerializePropertyAsElementUsing(typeof(T), 
               _expression.GetProperty(), 
               _expression.GetProperty().Name, 
               /*ERROR:*/ selector);
    return this;
}

...

The answer is actually so simple that I felt dumb for not seeing it immediately.  We can wrap our generic Func<T,object> inside a non-generic Func<object,object>.  The wrapper Func basically serves as an adapter, enabling us to pass an instance of one type to a method that only accepts an instance of another type:

ITypeSerializationSpec<T> IInitialPropertySerializationSpec<T>.Using(Func<T, object> selector)
{
    Func<object,object> wrapper = o => selector((T)o);
    
    //_config is of type ISerializationConfig. 
    _config.SerializePropertyAsElementUsing(typeof(T), 
               _expression.GetProperty(), 
               _expression.GetProperty().Name, 
               /* This works! */wrapper);
    return this;
}

I love it when there is a simple and elegant solution to a seemingly complex and nasty problem. :)

Tags:

Oct 4 2010

A More Fluent API For AutoMapper

Category: MiscMatt @ 12:25

I love AutoMapper.  I’ve used it in virtually every ASP.NET MVC application I’ve ever worked on.  It has saved me countless lines of tedious code, and it’s quite smart at inferring the correct mappings.  However, my one complaint is that the API for specifying the more complicated mappings is, in a word, ugly.  It’s flexible, sure, but ugly.  In this post, I’ll show you how a few simple extension methods that can make things much prettier.

First, let’s consider a very trivial (fictional) domain model and corresponding view model:

public class Widget
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class WidgetViewModel
{
    public string FullName { get; set; }
    public string Placeholder { get; set; }
}

Our mapping requirements here are quite simple: we want to concatenate FirstName and LastName and map it to the FullName property on the view model, and we want to ignore the Placeholder property entirely.  Here’s a class that creates exactly this mapping:

public class WidgetViewModelMap
{
    public void CreateMapping(IConfiguration mappingConfig)
    {
        mappingConfig.CreateMap<Widget, WidgetViewModel>()
            .ForMember(m => m.FullName, opt => opt.MapFrom(w => w.FirstName + " " + w.LastName))
            .ForMember(m => m.Placeholder, opt => opt.Ignore());
    }
}

The two ForMember calls are what I was referring to when I said “ugly”.  We have some nested lambdas going on here, which makes the code hard to read.  The IMappingConfiguration interface (the ‘opt’ parameter) provides a lot of functionality, but I’ve yet to need to call multiple methods on it at once.  I always use a single method, just like I’ve done in this example.  What I’d like to see instead is syntax more like this:

public class WidgetViewModelMap
{
    public void CreateMapping(IConfiguration mappingConfig)
    {
        mappingConfig.CreateMap<Widget, WidgetViewModel>()
            .ForMember(m => m.FullName).MapFrom(w => w.FirstName + " " + w.LastName)
            .ForMember(m => m.Placeholder).Ignore();
    }
}

It’s not a major change, but the nested lambdas are gone, and the code reads better IMO.  I could submit a patch with this change, wait for it to be evaluated and possibly incorporated, but why wait?  Thanks to the power of extension methods, I’ve already got all the tools I need to achieve this syntax right now!

First, we’ll need the ForMember extension method:

public static class AutoMapperExtensions
{
    public static MemberMappingExpression<T1,T2> ForMember<T1,T2>(this IMappingExpression<T1,T2> expression, Expression<Func<T2,object>> member)
    {
        return new MemberMappingExpression<T1,T2>(expression, member);
    }
}

Next, we’ll need to implement our MemberMappingExpression class:

public class MemberMappingExpression<T1,T2> : IMemberMappingExpression<T1, T2>
{
    private readonly IMappingExpression<T1, T2> _mappingExpression;
    private readonly Expression<Func<T2, object>> _member;

    public MemberMappingExpression(IMappingExpression<T1,T2> mappingExpression, Expression<Func<T2, object>> member)
    {
        _mappingExpression = mappingExpression;
        _member = member;
    }

    public IMappingExpression<T1,T2> MapFrom<TResult>(Func<T1, TResult> sourceMember)
    {
        _mappingExpression.ForMember(_member, opt => opt.MapFrom(sourceMember));

        return _mappingExpression;
    }

    public IMappingExpression<T1,T2> Ignore()
    {
        _mappingExpression.ForMember(_member, opt => opt.Ignore());

        return _mappingExpression;
    }
}

And TA-DA!  You now have a simpler, more fluent interface for defining your mappings.  Note that MemberMappingExpression should really be encapsulated behind an interface, and there are undoubtedly other methods that could be added besides the two I’ve implemented, but doing so is a trivial exercise. 

Tags: