To Node.js Or Not To Node.js

Node.js – it has rapidly become the “new hotness” in the tech start-up realm. With each passing day, the fan base of Node lovers grows larger, spreading their rhetoric like a religion. How do you spot a Node.js user? Don’t worry, they’ll let you know. ;)

One day you’re at a regular user group meeting, sipping soda and talking with some colleagues, when the subject turns to Node. “Have you guys tried Node.js?” asks one of the people in your group. “It’s all the rage. All of the cool kids in Silicon Valley are using it!” “What does it do?” you ask, only to be bombarded with a sales pitch worthy of the best of used car lots. “Oh, it’s amazing!” they reply, sipping their diet coke and shuffling their hipster fedora and backpack with MacBook Pro in it (or something like that), “It’s server side JavaScript. It runs on a single thread and it can do 100,000 web requests a second!” They glance at the group for the oohs and ahhs, but most people just stare back with amazement in their eyes. Then, your hipster Node-loving friend drops the words that start wars: “It’s way better than .NET” – and just like that, your group is hooked. They go home, download the Node.js tools, write “Hello World”, and suddenly they’re on their way to the next user group meeting to talk about how great Node is.

Okay, so I might be exaggerating the appearance and demeanour of your average Node lover a little (read: a lot, almost entirely in fact). However, I have had this exact scenario happen repeatedly over the last six months, with ever-increasing intensity and frequency. Node users love Node. They want you to love Node. They’re excited about it.

Having given it some thought, why wouldn’t Node.js developers be excited? Want to fire up a “Hello World” web server in Node? It’s trivial:

// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

Want to do the same thing in .NET? Be prepared to learn about IIS, the Machine.config, the Web.config, the Process Model, how Global.asax works, either ASP.NET MVC or WebForms (huge paradigms in themselves), and how Visual Studio works. Don’t forget to learn how to create a solution, at least one web project, and how to deploy the application to IIS. Oh, and one little detail: go ahead and learn C# while you’re at it. All of that’s pretty much just as easy and intuitive as Node.js, right?

.NET is incredibly complicated. Node.js is incredibly simple. On the merits of that fact alone it’s no wonder that these .NET developers and fresh-out-of-college kids who have already dabbled in JavaScript are transferring these skills to the server side and standing up web servers in literally 5 minutes and 5 lines of code. How can you deny the sexiness of that? The bragging rights it gives you? The ease and comfort of a language you’re already familiar with?

This, in my opinion, is why Node.js is becoming huge. It has simplified and streamlined the development process and made programming very accessible to almost everyone (or at least anyone who has ever played with JavaScript).

However, to those who sell Node.js as single-threaded, and to those who sell Node.js as having significantly better performance than .NET, I say this: you are wrong.

With simplicity comes misunderstanding and the concept of “Leaky Abstractions.” As my good friend and colleague Thomas B. said to me during dinner last week: Node.js is opinionated. It has an opinion on how you should do things, and it forces you to do them a certain way.

Node.js is not single-threaded, though many Node developers in my experience believe it to be. Node’s creator believes that a single-threaded listener delegating I/O-bound work to a thread pool is the key to a highly available application. As a result, Node.js forces you into this paradigm of event-based asynchronous execution of I/O operations via a thread pool.

Node.js has a single thread listening for connections. All of the code which you as the Node developer write is executed on this single thread. This single thread is all that is exposed to you. As soon as a connection is received, Node’s listening thread executes your coded event on the same listener thread. This event either does quick, non-CPU intensive work (like returning static content to a client), or long-running I/O bound operations (like reading data from a database). In the case of the former, the listener thread does in fact block for the duration of the request, but the request happens so quickly that the delay is trivial. In the case of the latter, Node uses V8 and libuv (which it is built upon) to delegate the I/O work to a thread from an underlying pool of native C++ threads. The single listening thread kicks off the work to an I/O worker thread with a callback that says “tell me when you’re done” and immediately returns to listening for the next connection. It is thus plain to see that Node.js is indeed multi-threaded, though this functionality is not directly exposed to the Node developer.

An important note regarding Node.js is that any CPU-intensive code which you write will block the entire system and make your application scale poorly or become entirely unresponsive. As a result, you would not want to use Node.js when you need to write an application that will do CPU-intensive work such as performing calculations or creating reports.

This is how a single thread can handle multiple requests at once; receiving a request and either serving static/simple content or delegating it to an I/O thread from a thread pool are both very cheap and quick operations. When the thread pool thread that is doing the long-running I/O work signals to the single listener thread that the work is done, the listener thread picks up the response and sends it back to the user; this is another very cheap operation. The core idea is that the single listener thread never blocks: it only does fast, cheap processing or delegation of requests to other threads and the serving of responses to clients. The diagram below (taken from Stack Overflow) explains this visually:

Node.js Processing Model

This is a very good, scalable, highly-available way to write code; Node.js nailed their approach and developers benefit from it. However, as of .NET 4.5, you can easily create this exact paradigm/pattern in your .NET applications. The difference is that .NET does not force you to do so.

With the introduction of a very tidy wrapper around asynchronous programming in .NET 4.5 (async/await keywords), Microsoft made asynchronous, event-based programming quite a bit easier and more intuitive. And with recent conformance by Microsoft to the jointly-created OWIN specification, the web pipeline of .NET has become much simpler.

In fact, you can now write the “Hello World” asynchronous web server in .NET in about as few lines as Node.js! In this example, I host a web server in a console application which is terminated when a key is pressed:

/// <summary>
/// A simple program to show off an OWIN self-hosted web app.
/// </summary>
public class Program
{
    /// <summary>
    /// The entry point for the console application.
    /// </summary>
    /// <param name="args">The arguments to the execution of the console application. Ignored.</param>
    static void Main(string[] args)
    {
        // Start OWIN host
        using (WebApp.Start<Startup>(url: "http://localhost:8000"))
        {
            // Runs until a key is pressed
            Console.ReadKey();
        }
    }

    /// <summary>
    /// This code configures the OWIN web app. The Startup class is specified as a type parameter in the WebApp.Start method.
    /// </summary>
    private class Startup
    {
        /// <summary>
        /// Configures the web app.
        /// </summary>
        /// <param name="app">The app builder.</param>
        public void Configuration( IAppBuilder app )
        {
            // We ignore any rules here and just return the same response for any request
            app.Run( context =>
            {
                context.Response.ContentType = "text/plain";
                return context.Response.WriteAsync( "Hello World\n" );
            } );
        }
    }
}

One of the big positives of Node.js is that you opt-in to complexity. You start very simply and add on functionality as you need it. I’m a big fan of this approach and I feel that this is where Node really shines. Nothing bothers me more than starting an “Empty MVC 4 Web Application” from template in Visual Studio only to have it install about 15 Nuget packages, one of which is Entity Framework. Great, I fired up a blank application and already my ORM has been decided for me. Who said I even needed one in the first place?!

The above OWIN-based approach to hosting a web app in .NET allows you to benefit from Node’s simplistic approach. I have started out simply, and can now add Dapper if I need an ORM, Newtonsoft.Json if I need to serialize to and from JSON, Unity if I care about dependency injection, etc. It’s a nice, clean slate upon which I can build any framework that I desire.

This approach in .NET is very comparable to Node.js, with a few differences:

  • Node.js uses 1 listener thread, while .NET uses N listener threads. If your Node.js application does CPU-intensive work at all, it will block the entire system and potentially cause your application to become unresponsive. .NET, on the other hand, is designed to do CPU intensive work. Tying up a thread to do some CPU work is not of concern because there are other threads available in the listener thread pool to take other requests while this is happening. However, both Node.js and .NET are limited by the server resources; in either case, if you max out the CPU or RAM, your app will perform horribly, regardless of thread delegation. This is known as resource contention.
  • Node.js delegates I/O bound work to an I/O thread worker pool, and .NET implemented asynchronously (async methods and the async/await keywords) does the same.
  • Node.js uses an event-based paradigm, and .NET does also when implemented asynchronously.
  • Node.js offers high performance for I/O bound, low CPU operations, and .NET offers comparable performance when you skip the IIS pipeline. IIS tacks on a significant amount of performance overhead due to things like session state management, forms authentication, the process model, request lifecycle events, etc. These are not bad things to have and use, but if you don’t need IIS, session state, forms auth, request lifecycle events, or the process model, then don’t use them!
  • Node.js must parse/serialize to and from JSON, and .NET must serialize to and from JSON to interact with .NET objects. Parsing is going to be much cheaper in Node.js than serializing is in .NET, but .NET also enables you to serialize to XML, Atom RSS, and anything else that you desire. With Node, this is a bit trickier, and the serialization overhead comes back into play to even the field.

When someone compares Node.js to .NET, I find that they often actually compare Node.js to IIS hosted frameworks such as ASP.NET MVC, ASP.NET WebForms, and ASP.NET Web API (in IIS hosted mode). These are all tools built on top of ASP.NET to simplify enterprise web development and to do CPU-intensive calculations. In these scenarios, Node.js will have an advantage, because it is designed specifically to NOT do CPU-intensive calculations. You are effectively comparing CPU-intensive Apples to low-CPU-usage Oranges. It is not a fair comparison.

When someone compares Node.js to a self-hosted .NET web app which does I/O-bound long-running operations via asynchronous thread pool delegation, they find that there is not much of a difference in performance between the two runtimes. In fact, comparing Node.js to self-hosted Web API (NOT using IIS) doing low-CPU work, the numbers are very close:

Web API vs Node.js

This image was taken from a benchmark done in 2012 with the Web API Release Candidate (not Web API 2, and NOT OWIN hosted). Given that Web API 2 exists, and can be self-hosted via OWIN, I’d love to see a more recent benchmark comparing the two. In fact, I will try and do this for my next blog post.

So, to Node.js or not to Node.js? I submit these final thoughts:

I guess the point of all of this has been that neither Node.js or .NET is necessarily better/the best/the new hotness. They both serve a purpose, and while Node.js is much easier to use and more accessible to developers, .NET is very versatile and powerful as well. They are built to do different things: Node.js specializes in performing and scaling well for low-CPU, highly I/O-bound operations. .NET can perform well in this scenario as well, but can also perform well with high-CPU operations. In fact, I would argue that .NET excels at CPU-intensive operations, especially when compared to Node.

There are many .NET developers in the current tech scene that are capable and competent. This means that it’s not too hard to find, hire, and retain good .NET talent. They can pick up self-hosted OWIN web apps in a matter of days, and begin to write very scalable, high-performance web apps and services based on it. They can even easily host Web API in an OWIN web app via console, a Windows service, or Azure. There’s a community that has existed for over a decade that evolves the .NET framework with amazing tools and add-ons like Dapper, Unity, and Newtonsoft.Json. This community is mature and there are many prominent voices within it that offer advice and help.

Relative to .NET, there aren’t as many Node.js developers in the current tech scene that are capable and competent. This is because fortune favours the bold, and only a few have been early adopters of Node.js. In my experience, few Node developers will truly understand what is going on in the Node.js processing model and how to exploit it for maximum performance, though the opinionated paradigm of Node.js will force developers to write good asynchronous code. It can be hard to find, hire, and retain good Node.js talent. This will become less of a concern as Node’s following grows. The Node.js community is budding and has created some amazing tools and add-ons for Node.js as well such as ORMs and DI frameworks. This community is not yet mature and I am not aware of many prominent voices within it that offer advice and help. As a result, it could be difficult to find support and tools for Node.js if you encounter a problem.

In conclusion, both Node.js and .NET are great. Which one to pick for a particular solution/application, however, depends on many factors; it is not black and white but a full colour spectrum. It would be very foolish and naive for a .NET developer to use .NET to solve every single problem just because “that’s what we use.” It would be similarly foolish for a Node.js developer to propose Node.js as a solution for every project or problem that he or she encounters. One must choose the right tool for a given job, and be open to different paradigms in order to truly excel.

In general, use Node.js when you have highly I/O-bound operations that don’t use much CPU. Use .NET when you need to calculate things and use a lot of CPU.

Don’t use Node.js solely on the reasoning that it’s much faster and performs way better than .NET: it depends on how you use .NET. And don’t use .NET if all you’re doing is heavily I/O-bound operations with low CPU usage: that’s where Node.js excels.

C# Probably Getting New “Safe Navigation” Operator “?.”

It looks as if the Visual Studio dev team may be implementing a new operator in a future .NET release. This is due in large part to community demand, which is pretty cool because it shows that the VS team is listening to their customer base; a key part of a successful product.

This new operator is likely going to take the syntax of ?. and is known as the Safe Navigation Operator.

Its purpose is rather simple, and it eliminates a load of boiler-plate code by making the compiler do it for you.

Say you have these classes:

public class A
{
    public B B { get; set; }
}

public class B
{
    public C C { get; set; }
}

public class C
{
    public int D { get; set; }
}

It’s plain to see above that it’s possible that an instance of A may have a null B property, or even that an instance of B may have a null C property. If you want to get D from A safely (so as to avoid null reference exceptions), your code often ends up looking something like this:

int? result = A.B == null ? (int?)null : 
    (A.B.C == null ? (int?)null : A.B.C.D);

What an incredibly annoying pain to write out, and even to read. You could maybe make it clearer, at the cost of more verbosity and lines of code:

int? result = null;
if (A.B != null)
{
    if (A.B.C != null)
    {
        result = A.B.C.D;
    }
}

This is still a bit convoluted and boiler-plate for my liking. Really, all we want to do in English is get the integer value of D if it exists on A. It shouldn’t be so challenging!

Enter the new Safe Navigation Operator and how it might function:

int? result = A?.B?.C.D;

Note the ?. that is placed at the point where the A instance references B and B instance references C. This is much more readable, and intuitive to look at. To me, it says “if A’s B is not null and B’s C is not null, return D, else return null” which is pretty streamlined. Upon simple inspection, it also clearly says that A.B is nullable and B.C is nullable, which are great side effects of the shortened syntax.

Note that the final product, if included in C#, may behave differently than I’ve demonstrated and hypothesized here. The code in this post is mostly made on assumptions of compiler rules for this operator, and could in the future prove to be wrong. However, even still, this operator will be a great addition to C# and .NET if it makes the cut!

Trigger IValidatableObject.Validate When ModelState.IsValid is false

I recently came across an ASP.NET MVC issue at work where the validation for my Model was not firing correctly. The Model implemented the IValidatableObject interface and thus the Validate method which did some specific logic to ensure the state of the Model (the ModelState). This Model also had some DataAnnotation attributes on it to validate basic input.

Long story short, the issue I encountered was that when ModelState.IsValid == false due to failure of the DataAnnotation validation, the IValidatableObject.Validate method is not fired, even though I needed it to be. This problem arose due to a rare situation in which ModeState.IsValid was initially false but was later set to true in the Controller’s Action Method by some logic that removed errors from the ModelState.

I did some research and learned that the DefaultModelBinder of ASP.NET MVC short-circuits it’s logic: if the ModelState is not valid (AKA is false), the IValidatableObject logic that runs the Validate method is never fired.

To thwart this, I created a custom Model Binder, a custom Model Binder Provider (to serve my custom Model Binder), and then registered the Model Binder Provider in the Application_Start method of Global.asax.cs. Here’s the code for a custom Model Binder that always fires the IValidatableObject.Validate method, even if ModelState.IsValid == false:

ForceValidationModelBinder:

/// <summary>
/// A custom model binder to force an IValidatableObject to execute the Validate method, even when the ModelState is not valid.
/// </summary>
public class ForceValidationModelBinder : DefaultModelBinder
{
    protected override void OnModelUpdated( ControllerContext controllerContext, ModelBindingContext bindingContext )
    {
        base.OnModelUpdated( controllerContext, bindingContext );

        ForceModelValidation( bindingContext );
    }

    private static void ForceModelValidation( ModelBindingContext bindingContext )
    {
        // Only run this code for an IValidatableObject model
        IValidatableObject model = bindingContext.Model as IValidatableObject;
        if( model == null )
        {
            // Nothing to do
            return;
        }

        // Get the model state
        ModelStateDictionary modelState = bindingContext.ModelState;

        // Get the errors
        IEnumerable<ValidationResult> errors = model.Validate( new ValidationContext( model, null, null ) );

        // Define the keys and values of the model state
        List<string> modelStateKeys = modelState.Keys.ToList();
        List<ModelState> modelStateValues = modelState.Values.ToList();

        foreach( ValidationResult error in errors )
        {
            // Account for errors that are not specific to a member name
            List<string> errorMemberNames = error.MemberNames.ToList();
            if( errorMemberNames.Count == 0 )
            {
                // Add empty string for errors that are not specific to a member name
                errorMemberNames.Add( string.Empty );
            }

            foreach( string memberName in errorMemberNames )
            {
                // Only add errors that haven't already been added.
                // (This can happen if the model's Validate(...) method is called more than once, which will happen when there are no property-level validation failures)
                int index = modelStateKeys.IndexOf( memberName );

                // Try and find an already existing error in the model state
                if( index == -1 || !modelStateValues[index].Errors.Any( i => i.ErrorMessage == error.ErrorMessage ) )
                {
                    // Add error
                    modelState.AddModelError( memberName, error.ErrorMessage );
                }
            }
        }
    }
}

ForceValidationModelBinderProvider:

/// <summary>
/// A custom model binder provider to provide a binder that forces an IValidatableObject to execute the Validate method, even when the ModelState is not valid.
/// </summary>
public class ForceValidationModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder( Type modelType )
    {
        return new ForceValidationModelBinder();
    }
}

Global.asax.cs:

protected void Application_Start()
{
    // Register the force validation model binder provider
    ModelBinderProviders.BinderProviders.Clear();
    ModelBinderProviders.BinderProviders.Add( new ForceValidationModelBinderProvider() );
}

MVC4 Conditional HTML Attributes

MVC4 made one simple and yet awesome improvement to View rendering that I don’t think many people are aware of.

Have you ever had to conditionally add an attribute to an HTML element in your MVC View based on the presence of a variable? The typical use case is applying a CSS class to a div. Most of the time that code looks something like this:

<div @(myClass == null ? "" : "class=\"" + myClass + "\"")></div>

What a pain – not only to write but to read… This destroys the View’s readability and clutters the HTML up big time!

In MVC4, this process is much simpler. Just do this instead:

<div class="@myClass"></div>

That’s all you need. If myClass is null, it will ignore the class attribute and render without the class:

<div></div>

If myClass is not null, it will apply the class to the div:

<div class="test"></div>

This should work with other HTML element attributes also, though I haven’t tested them all myself. What a great little improvement!

Dache is now Open Source

In my spare time over the last year or so, I’ve been writing a distributed caching solution for .NET called Dache. I built it because after using both AppFabric and CouchBase in a corporate environment which had significant load (> 30000 concurrent users), I felt that they both fell short of their potential. AppFabric requires installing PowerShell and a ton of other stuff, and reserves 50% of the server’s RAM for internal use leaving only the other 50% of the memory available for caching. CouchBase operates reasonably well but doesn’t really keep up with load, offering lower operations per second than other solutions. Our company talked to NCache and felt that their system was overpriced and didn’t deliver the features that we wanted. As a result, I cranked out Dache in my spare time as a native .NET solution that out-performs the competition.

Though I was originally going to sell the solution, I recently chose to make Dache open source and released it to GitHub. At the same time, I overhauled the website with a new layout that I’m very fond of. Ultimately I just want the .NET community to have access to good, stable distributed caching software that doesn’t require Linux to host.

Tonight I launched version 1.1.0 of Dache, which offers performance increases over 1.0.0 and simplifies the solution quite a bit. In particular it adds some neat features around the bulk API and tagging system to maximize the throughput of these features.

If you have a need for a distributed caching solution, please give Dache a go! I love feedback, so feel free to contribute on GitHub, contact me, or leave comments!

http://www.getdache.net

Automatically Generate POCOs From DB With T4

The T4 template engine is insanely powerful. I didn’t really realize just how powerful it was until I had a use case for it today. I stood up a database with about 40 tables in it, and planned to use an ORM to access the database. To use the ORM, I needed POCOs (Plain Old C# Objects) that represented my database. Some of these tables had 30-50 or so columns and I didn’t want to code all of this by hand – it would take literally days.

Surprisingly, I got the whole thing done in about an hour with the help of the T4 template engine.

For those who are not familiar, T4 is a text template engine created by Microsoft which combines plain text and control logic to generate text output. In reality it’s a lot like how you use Razor or WebForms view engines to generate HTML; you can embed “code nuggets” almost exactly like you do in WebForms. The only real difference is that with T4 you’re creating a text file instead of a webpage.

To create a T4 template in Visual Studio 2010 or 2012, simply add a text file to your project… I called mine PocoGenerator.txt for example. Then, rename the file’s extension from “.txt” to “.tt” – the file will then be treated as a T4 Template by Visual Studio. Your output will appear in the code-behind .cs file attached to the .tt file you just created. In my scenario I wanted each of my POCOs to have their own file, so I did a bit of trickery to make that happen.

I wrote this nifty T4 template which connects to a database, queries all tables (ignoring sys tables), and then creates one POCO per table under a file named <tablename>.cs which is placed in a directory relative to the template’s location. Give this a go – you won’t be disappointed! And of course, if you need it to do more than I do, just modify it and make it your own!

<#@ template language="C#" hostspecific="true" debug="True" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="Microsoft.SqlServer.Smo" #>
<#@ assembly name="Microsoft.SqlServer.ConnectionInfo" #>
<#@ assembly name="Microsoft.SqlServer.Management.Sdk.Sfc" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="Microsoft.SqlServer.Management.Smo" #>
<#
    //**********************************************************************************************
    // This T4 generates POCOs from the specified DB and saves them to the specified folder which 
    // is relative to the template's location. One file per table/POCO.
    //**********************************************************************************************

    //****************************
    // DEFINE YOUR VARIABLES HERE
    //****************************
    // The SQL server name or IP
    string sqlServer = "9.9.9.9";
    // The SQL username
    string sqlLogin = "admin";
    // The SQL password
    string sqlPassword = "password";
    // The SQL database to generate the POCOs for
    string sqlDatabase = "MyDatabase";
    // The namespace to apply to the generated classes
    string classNamespace = "Your.Namespace.Here";
    // The destination folder for the generated classes, relative to this file's location.
    string destinationFolder = "PocoFolder";

    // Loop over each table and create a class file!
    Server server = new Server(sqlServer);
    server.ConnectionContext.LoginSecure = false;
    server.ConnectionContext.Login = sqlLogin;
    server.ConnectionContext.Password = sqlPassword;
    server.ConnectionContext.Connect();

    foreach (Table table in server.Databases[sqlDatabase].Tables)
    {
        // Skip sys tables
        if (table.Name.StartsWith("sys"))
        {
            continue;
        }
#>
using System;

namespace <#= classNamespace #>
{
    /// <summary>
    /// Represents a <#= table.Name #>.
    /// NOTE: This class is generated from a T4 template - you should not modify it manually.
    /// </summary>
    public class <#= table.Name #> 
    {
<# 
        // Keep count so we don't whitespace the last property/column
        int columnCount = table.Columns.Count;
        int i = 0;

        // Iterate all columns
        foreach (Column col in table.Columns)
        {
            i++;
            string propertyType = GetNetDataType(col.DataType.Name);

            // If we can't map it, skip it
            if (string.IsNullOrWhiteSpace(propertyType))
            {
                // Skip
                continue;
            }

            // Handle nullable columns by making the type nullable
            if (col.Nullable && propertyType != "string")
            {
                propertyType += "?";
            }
#>
        public <#= propertyType #> <#= col.Name #> { get; set; }
<#
            // Do we insert the space?
            if (i != columnCount)
            {
#>

<#
            }
#>
<#
        }
#>
    }
}      
<#
        // Write new POCO class to its own file
        SaveOutput(table.Name + ".cs", destinationFolder);
    } 
#>
<#+
    public static string GetNetDataType(string sqlDataTypeName)
    {
        switch (sqlDataTypeName.ToLower())
        {
            case "bigint":
                return "Int64";
            case "binary":
            case "image":
            case "varbinary":
                return "byte[]";
            case "bit":
                return "bool";
            case "char":
                return "char";
            case "datetime":
            case "smalldatetime":
                return "DateTime";
            case "decimal":
            case "money":
            case "numeric":
                return "decimal";
            case "float":
                return "double";
            case "int":
                return "int";
            case "nchar":
            case "nvarchar":
            case "text":
            case "varchar":
            case "xml":
                return "string";
            case "real":
                return "single";
            case "smallint":
                return "Int16";
            case "tinyint":
                return "byte";
            case "uniqueidentifier":
                return "Guid";
                
            default:
                return null;
        }
    }

    void SaveOutput(string outputFileName, string destinationFolder)
    {
        // Write to destination folder
        string templateDirectory = Path.Combine(Path.GetDirectoryName(Host.TemplateFile), destinationFolder);
        string outputFilePath = Path.Combine(templateDirectory, outputFileName);
        File.Delete(outputFilePath);
        File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); 

        // Flush generation
        this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
    }
#>

Note that when the files are generated, they will not automatically be included in the project. You will have to add them manually as existing items.

This T4 Template supports regeneration, so anytime you update your database schema just re-run the template to create updated .cs files! Enjoy!

Time to Try Something New

I read a lot of other programming blogs. After all, gathering information from multiple sources is a great way to get a rounded education. Every so often, the author of a blog gets a new job and writes a blog post about the transition to the new job and rationalization of leaving the current job. I’m certainly not against such posts (I definitely read them) but I must admit that I don’t feel that they actually contribute anything useful to anybody other than the author. I believe that each person is unique, and their career is a personal, private, proud, unique part of them. People typically do things and make decisions during their career to further themselves. Some of these actions and decisions end up being good and others bad. However, regardless of outcome, the decision or action is made for reasons that are entirely the person’s own and relative to their unique circumstance. What motivates person A to work at company X won’t motivate person B and so forth.

So while I enjoy reading posts that explain how the author feels that they’ve been at their job for too long, or they aren’t yet on the latest .NET framework and are falling behind, or they feel that getting into a new industry or vertical is a good idea, the reality is that these reasons are them rationalizing the decision to themselves. The post as a result is self-serving… As is mine that you’re reading now.

In light of this mindset, I will keep the actual announcement part of my “new job” post short and sweet.

While I had a great time working with Fanatics and helping them grow from a brick-and-mortar sports store to the e-commerce platform that hosts such juggernauts as the official NFL, NBA, NASCAR, MLB, NHL, and ESPN stores, it is time for me to move on and do something new. As of Monday, September 30th I’ll be working at iMobile3 – a mobile application and wallet/payment service company based out of Jacksonville. I am extremely excited to be able to contribute to such an interesting product and to have the opportunity to have a direct impact on the company’s future successes and growth.

Here comes the next adventure; a new experience and opportunity. I’m very excited.

Presented at Code on the Beach

Today I presented to Code on the Beach. My topic was “HOW TO BUILD A MILLION USER ASP.NET MVC WEB APP”. I had a great time and I personally feel that it was my best talk yet. What really made it great was the awesome audience and questions asked.

A copy of the presentation which I did and the example code is available here.

Thanks again for the opportunity Code on the Beach! It has been a terrific conference.