I Am Not Myself

Bills.Pay(Developer.Skills).ShouldBeTrue()

Category Archives: Uncategorized

Useful Tool of the Day: smtp4dev

We send a lot of emails to our users at Cheezburger. Sign up for an account, get a new user email. Submit some funny content, get a message with a link to the content so you can find it. Make the homepage and get a congratulatory message. You get the idea. As you can image our marketing team loves to wordsmith and prettify these messages. So we update them often.

I primarily work out of a Virtual Machine and try to keep running background tasks to a minimum. So, I don’t particularly want a SMTP server running unless I am actively working on email code. Enter smtp4dev, a simple light weight dummy SMTP server. It runs in your system tray and gives you an easy way to capture email messages and view them.

So some simple code like this

using System.Net.Mail;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var message = new MailMessage("dirk@diggler.com", "jack@horner.com")
                {
                    Subject = "I AM THE STAR!",
                    Body = @"You're not the boss of me, Jack. You're not the king
                            of Dirk. I'm the boss of me. I'm the king of me. I'm 
                            Dirk Diggler. I'm the star."
                };

            new SmtpClient("localhost", 25)
                .Send(message);

        }
    }
}

smtp4dev will capture it like this

MvFABVU

You can simply double click the message and open the EML file in your default email application to view it.

PROTIP: Haters Gonna Hate

Keep moving forward. Don’t let the world hold you back.

 

Using the Implicit Operator in C# for Maximum Nerdy Good Times

My current team works with a lot of data. We represent that data with explicit types. For example if a string represents a Name we create an explicit type called Name like so:

public struct Name
{
  private readonly string _string;
  public Name(string name){ _string = name; }
  public override string ToString() { return _string } 
}

This makes things nice for testing purposes as these value structs are comparable for free and are clearly named what the value represents. The downside is if you need to set up a bunch of test data for a unit test you can run into code that looks like this:

 Name name = new Name("Name");
 IEnumerable<Name> names = new[] { new Name("Tom"), new Name("Dick"), new Name("Harry"), }

This will quickly give you carpal tunnel with all the ceremony required to create all the instances. It would be nice if we could reduce some of the noise and we can via use of the implicit operator. All we need to do is add the following operator logic to our struct.

public struct Name
{
  private readonly string _string;
  public Name(string name){ _string = name; }
  public override string ToString() { return _string } 
  public static implicit operator Name(string name) { return new Name(name); }
}

What does this buy us? How does the following syntax strike you?

 Name name = "Name";
 IEnumerable<Name> names = new[] { "Tom", "Dick", "Harry", }

We are used to using implicit typing from on the left hand side of a statement, were you aware that it can be used on the right hand side? I wasn’t. But basically this is how collection initializers work. Nice eh?

Thanks to Robert Ream for showing me this. It was fun working with someone with such a deep understanding of the language and functional development, even if it was a brief time.

Glenn Block Node.js on Windows Azure Video

Overview

If I told you that you can build node.js applications in Windows Azure would you believe me? Come to this session and I’ll show you how. You’ll see how take those existing node apps and easily deploy them to Windows Azure from any platform. You’ll see how you can make yours node apps more robust by leveraging Azure services like storage and service bus, all of which are available in our new “azure” npm module. You’ll also see how to take advantage of cool tools like socket.io for WebSockets, node-inspector for debugging and Cloud9 for an awesome online development experience.

About Glenn

Glenn is a PM at Microsoft working on support for node.js in Windows and Azure. Glenn has a breadth of experience both both inside and outside Microsoft developing software solutions for ISVs and the enterprise. Glenn has been a passionate supporter of open source and has been active in involving folks from the community in the development of software at Microsoft. This has included shipping products under open source licenses, as well as assisting other teams looking to do so. Glenn is also a lover of community and a frequent speaker at local and international events and user groups.

Glenn’s blog can be found on CodeBetter or you can follow him on twitter at you own risk.

Video

Slides

Source

The source for this presentation can be found on Adron’s github account.

SSDNUG Presents: Glenn Block – Unlock your inner node in the cloud with Windows Azure

The South Sound .NET Users group is proud to present Glenn Block on Thursday March tth at 7:00PM at the Olympia Center in the heart of downtown Olympia, WA.

If I told you that you can build node.js applications in Windows Azure would you believe me? Come to this session and I’ll show you how. You’ll see how take those existing node apps and easily deploy them to Windows Azure from any platform. You’ll see how you can make yours node apps more robust by leveraging Azure services like storage and service bus, all of which are available in our new “azure” npm module. You’ll also see how to take advantage of cool tools like socket.io for WebSockets, node-inspector for debugging and Cloud9 for an awesome online development experience.

Glenn is a PM at Microsoft working on support for node.js in Windows and Azure. Glenn has a breadth of experience both both inside and outside Microsoft developing software solutions for ISVs and the enterprise. Glenn has been a passionate supporter of open source and has been active in involving folks from the community in the development of software at Microsoft. This has included shipping products under open source licenses, as well as assisting other teams looking to do so. Glenn is also a lover of community and a frequent speaker at local and international events and user groups.

Glenn’s blog can be found on msdn or you can follow him on twitter at you own risk.

The Current Deployment Process for Simple.Data.Sqlite

On Friday, I picked up a copy of Camtasia:Mac by Techsmith. I have been doing screencasts with the Windows version for a year or so now, but I wanted something that would allow me to produce videos captured in both Windows and OSX.

I wanted an excuse to produce a video in OSX to try it out and see what the editing experience is like. I have been maintaining a Sqlite provider for Simple.Data and the update process is, in my opinion, pretty slick.

So, here you go, my first OSX produced video.

De Morgan’s Laws: Boolean Logic Is Serious Business

Today, Alex and I were pairing on a bug in our system dealing with an editor screen. Some properties of the item being edited are not editable based on the value of other properties of the item. This is implemented in the system fairly easily as a series of “can edit” like methods on the item’s view model.

The original code containing the bug looked like this:

private static bool IsInitializedAvailable(ModuleClass moduleClass, Indices indices)
{
    return moduleClass != ModuleClass.Liability && indices != Indices.Constant;
}

The bug stated that ArbitraryIndex was also a invalid value for indicies. This sounded like a simple enough fix to Alex and I. And we quickly implemented this:

 private static bool IsInitializedAvailable(ModuleClass moduleClass, Indices indices)
 {
     return moduleClass != ModuleClass.Liability && (indices != Indices.Constant || indices != Indices.ArbitraryIndex);
 }

This failed our unit test. In attempting to figure out why, I used a technique I have used in the past for figuring out boolean logic. I broke the comparisons out into separate pieces. So I could understand the logic of them better. Like so:

 private static bool IsInitializedAvailable(ModuleClass moduleClass, Indices indices)
 {   
    var isLiability = moduleClass == ModuleClass.Liability;
    var isConstantOrArbitraryIndex = indices == Indices.Constant || indices == Indices.ArbitraryIndex;
    
    return !isLiability && !isConstantOrArbitraryIndex;
}

This actually passed the tests, so we reconstituted the one-liner to get rid of the unneeded variables. Like so:

 private static bool IsInitializedAvailable(ModuleClass moduleClass, Indices indices)
 {   
    return moduleClass != ModuleClass.Liability && !(indices == Indices.Constant || indices == Indices.ArbitraryIndex);
}

Both Alex and I were uncertain why there was a difference between the original bug fix implementation and the final correct implementation. The two statements appear on the surface to be the same at a glance. Take a look yourself, can you spot the difference?

    moduleClass != ModuleClass.Liability && !(indices == Indices.Constant || indices == Indices.ArbitraryIndex); //wrong
    moduleClass != ModuleClass.Liability && (indices != Indices.Constant || indices != Indices.ArbitraryIndex);//correct

Alex, and I were stumped. That is when Alex’s CompSci degree from U of W woke up and he diagrammed out a Truth Table for the boolean expressions. It looked like this:

He went on to explain that boolean logic actually has clearly defined laws known as De Morgan’s Laws.

The rules can be expressed in English as:

“The negation of a conjunction is the disjunction of the negations.” and
“The negation of a disjunction is the conjunction of the negations.”

I am going to have to read up on both as they sound like a significant hole in my developer tool box. Thanks, Alex!

Introducing Giles: The Friendly Test Watcher

Bug slayer for great justice. Be sure to watch in HD full screen for maximum awesomeness.

Seriously Good Advice

I’ll say that learning to create software changes you and makes you different. Not better or worse, just different. You may find that people treat you harshly because you can create software, maybe using words like “nerd”. Maybe you’ll find that because you can dissect their logic that they hate arguing with you. You may even find that simply knowing how a computer works makes you annoying and weird to them.

To this I have one just piece of advice: they can go to hell. The world needs more weird people who know how things work and who love to figure it all out. When they treat you like this, just remember that this is your journey, not theirs. Being different is not a crime, and people who tell you it is are just jealous that you’ve picked up a skill they never in their wildest dreams could acquire.

Advice From An Old Programmer

Using Fluent NHibernate ClassMaps? You’re Doing It Wrong.

After some internal conversations at work, I tweeted that using ClassMaps with Fluent NHibernate is the the wrong way to approach the problem. This of course was a snarky in the moment tweet as is the title of this post, but I do actually think that auto mapping is the best usage pattern for Fluent NHibernate. And I wanted to expand on that a bit and share my reasoning.

The primary reason people use Fluent NHibernate is to get away from xml based mapping files that look like this.

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
    namespace="QuickStart" assembly="QuickStart">
    <class name="Cat" table="Cat">
        <!-- A 32 hex character is our surrogate key. It's automatically
            generated by NHibernate with the UUID pattern. -->
        <id name="Id">
            <column name="CatId" sql-type="char(32)" not-null="true"/>
            <generator class="uuid.hex" />
        </id>
        <!-- A cat has to have a name, but it shouldn' be too long. -->
        <property name="Name">
            <column name="Name" length="16" not-null="true" />
        </property>
        <property name="Sex" />
        <property name="Weight" />
    </class>
</hibernate-mapping>

All of this xml goo can be replaced with a simple ClassMap that allows you to take advantage of intellesense (which technically you don’t lose with hbm files if you have your project setup right). It would look something like this.

public class CatMap : ClassMap<Cat>
    {
        public CatMap()
        {
            Id(x => x.Id).GeneratedBy.UuidHex("B");
            Map(x => x.Name)
                .WithLengthOf(16)
                .CanNotBeNull();
            Map(x => x.Sex);
            Map(x => x.Weight);
        }
    }

What have we gained by doing this? The ClassMap is just as terse as the xml. We have simply avoided having to soil our fingers with the act of typing xml. The real power with FNH is when we start moving toward convention over configuration. Our mapping then becomes as simple as this.

AutoMap.AssemblyOf<IEntity>();

This will map all of the types located in the assembly containing the type IEntity. But let’s say that you want to constrain the mapping to only types in that assembly that implement the interface IEntity or are in a specific namespace. We can specify that by providing an implementation of DefaultAutoMappingConfiguration like this.

public class AutomappingConfiguration : DefaultAutomappingConfiguration
    {
        public override bool ShouldMap(Type type)
        {
            return type.Namespace.StartsWith("Core.Model") && 
                   type.GetInterfaces().Any(y => y == typeof(IEntity));

        }

    }

AutoMap.AssemblyOf<IEntity>(new AutomappingConfiguration());

There are several methods that can be overridden globally via the automapping configuration like this. By default FNH will assume any property with the name Id is the unique identifier for that type. Maybe for some reason you want to be the property named Guid. Simply add this override to your configuration.

public class AutomappingConfiguration : DefaultAutomappingConfiguration
    {
        public override bool IsId(Member member)
        {
            return member.Name == "Guid";
        }
    }

FNH comes with a set of sensible defaults but they can be easily replaced with conventions that better match your particular database schema. In a recent project that I was on, the DBA used schemas heavily. I decided to partition my domain model using the same schema structure and put my entities in different namespaces. I then added the following convention to my automapping.

public class TableNameConvention : IClassConvention
    {
        public void Apply(IClassInstance instance)
        {
            var schema = instance.EntityType.Namespace.Split('.').Last();
            var typeName = instance.EntityType.Name;
            var tableName = "[{0}].t_{1}".FormatWith(schema, typeName);

            instance.Table(tableName);
        }
    }
AutoMap.AssemblyOf<IEntity>(new AutomappingConfiguration())
                          .Conventions.AddFromAssemblyOf<AutomappingConfiguration>()

The auto mapper call then just needs know where to pick up the custom conventions. Maybe your database does not completely follow a standard convention. Maybe it has two completely different conventions for table naming. Feel free to add as many implementations of IClassConvention as you need and then specify what they apply to by implementing IClassConventionAcceptance as well like this. Each of the convention interfaces have a corresponding acceptance interface.

public class TableNameConvention : IClassConvention, IClassConventionAcceptance
    {
        public void Apply(IClassInstance instance)
        {
            var schema = instance.EntityType.Namespace.Split('.').Last();
            var typeName = instance.EntityType.Name;
            var tableName = "[{0}].t_{1}".FormatWith(schema, typeName);

            instance.Table(tableName);
        }

        public void Accept(IAcceptanceCriteria<IClassInspector> criteria)
        {
            criteria.Expect(x => x.Name.StartsWith("foo"));
        }
    }

By far the most common response I got to my twitter sniping was the “My database is special and I have to use class maps to map it because it’s so weird” excuse. And I completely sympathize with inheriting a messy database schema. For each of the types that do not map cleanly you can provide an override like this.

public class SecurityOverride : IAutoMappingOverride<Security>
    {
        public void Override(AutoMapping<Security> mapping)
        {
            mapping.Table("[PortfolioData].[t_LocalSecurityData]");
            mapping.Id(x => x.ID, "SecurityID");
            mapping.Map(x => x.Name, "SecurityName");
            mapping.Map(x => x.Type, "SecurityType");
        }
    }

AutoMap.AssemblyOf<IEntity>(new AutomappingConfiguration())
                          .Conventions.AddFromAssemblyOf<AutomappingConfiguration>()
                          .UseOverridesFromAssemblyOf<AutomappingConfiguration>();

Notice that the auto mapping override looks surprisingly like a class map. In fact anything you can do in a class map you can do with an override. So why not choose today to begin introducing sensible conventions to your data model? Use auto mapping to map new tables and tables that get refactored to the new convention based schema. This puts you in a good place to make improvements on your schema easily instead of simply replacing xml configuration with c# class map configuration.