# Angular Part 1: Show and Hide

This week, I have been diving headfirst into AngularJS. I am amazed at how much one can accomplish with very little code. In this example, I want to show and hide various parts of a form based on what selections the user makes elsewhere. That’s a pretty simple thing to do with jQuery. It’s even easier with AngularJS.

First, let’s show our base markup. This is the bare minimum to get our page to work.

The above HTML will render as follows.

If we already know jQuery, we know that we need to add a little more to our markup to make it play nice with jQuery.

1. Add an ID to our select box.
2. Add an ID to our wrapper div tag for our “Other” input.
3. Hide the “Other” form field by default.
4. Write a little bit of jQuery.

That’s really not too bad. Let’s however, add a few more requirements.

1. The Favorite Color option needs to be required.
2. The Other field needs to be required if Other is selected.
3. Don’t let the user submit an invalid form.

HTML 5 gives us some of this, but we still run into walls. We’re going to have to add a disabled attribute to the button. We’re going to have to validate our form with another library (or roll our own). We need to add required to the select box. We need to add required to our text box, but only if “Other” is selected.

The program flow should look like this.

This is the default state of the form.

User selects an option that is not “Other”. Everything is good. Enable the submit button.

User select “Other”. Show a text box and disable the submit button.

User enters a value in the text box. Everything is good again. Enable the submit button.

Again, none of this is particularly difficult, but you can imagine how all of this blows up when a page gets to be of a certain complexity. Let’s see what AngularJS has to offer.

1. Add ng-model tags to the form fields that we need to expose to angular. That’s both of them.
2. Add ng-required to any field that is dynamically required.
3. Add ng-disabled to any field that is dynamically disabled.
4. Wire it all together.

Let’s look at our AngularJS markup

Let’s compare our jQuery markup with our AngularJS markup.

1. The body tag now has an ng-app="" attribute. This is what tells Angular that it should work.
2. We have added a name="form" attribute to our form. By giving the form a name, it can be accessed by Angular. This access can be seen on the submit button, with the form.\$invalid variable.
3. We have added ng-model="..." to both of our input fields. This exposes the form fields to Angular.
4. We have added a required HTML5 attribute to our select.
5. We have added ng-show="favoriteColor === 'Other'" to our div tag that wraps our text box. This means that the field will only be shown if the expression is truthy.
6. We added an ng-required attribute to our text box. This means the field will be required if the expression is truthy.
7. Finally, we added an ng-disabled attribute to our button. This means that the button will be disabled if the expression is truthy.

Now, let’s show the JavaScript we need to write to make all this magic happen.

Yep. We’re done. Zero lines of JavaScript. Yeah, I could get used to this.

# Oops! How to Permanently Delete a File From Git

I accidentally added an uninitialized (appended) SQL Server backup file, a *.bak, to source control and pushed it. Now, no one can fetch a clean copy of the source because of out-of-memory errors. How do I fix this?

This will take a while to run, as it goes through every commit in your project and deletes the file. When you’re done, you’ll need to push the file to your remote.

You’ll need the --force flag because this is not a fast-forward commit.

# Getting Started With MathJax

I’ve spent the past few days getting myself reacquainted with TeX and familiarizing myself with MathJax. As it turns out, it is quite easy to get MathJax working in Octopress.

1. Open source/_includes/custom/head.html.
2. Add the a JavaScript source: //cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_HTMLorMML.
3. Start typing your TeX.
4. In your Gemfile, make sure you are using at least RDiscount version 2.1. gem 'rdiscount', '~> 2.1'
5. In your _config.yml file, disable automatic superscripts by adding - no_superscript to your RDiscount configuration.

The last two are quite important. Without those two steps, it looks like RDiscount will turn x^2 into x<sup>2</sup>. This will get displayed as x2. That will break the MathJax processor.

Let’s start by demonstrating a simple inline equation, like $$y = mx + c$$. This is simple enough by including the inline text: \$$y = mx + c \$$.

To enter full equations, like the one below, use the following syntax.

The above code will render as the following equation.

$$x = \dfrac{ -b \pm \sqrt{ b^2 - 4ac } }{ 2a }$$

Happy mathing!

# Mocking a JavaScript Constructor

JavaScript, and dynamic languages in general, make it extremely easy to mock out functions. This greatly reduces the need for all the extra programming junk (interfaces, adapters, wrappers, factories, etc.) that gets in the way of us solving our problems. We add tons of extra layers in the name of test isolation and object independence that plainly isn’t necessary in the dynamic languages world.

We’ve defined a very simple class, and it has all of the parts that we need to demonstrate how mocking works.

First, let’s define some simple tests. I’m using Jasmine and Node. (See jasmine-node for a command line version of Jasmine.) These tests fully describe the basic functionality of the class.

### Mocking an instance function.

The distanceTo() function exists on the instance of Point. It’s incredibly easy to mock out. Functions are first-class members in JavaScript, so we can simply redefine the function in the unit test. In this example, we simply redefine the function to return 0.

### Mocking a class function.

The origin() function is a class function that returns the point {0, 0}. Let’s suppose we need to define a different origin. That’s easy to do!

In this case, we need to store the original definition of origin() in the temp variable. In beforeEach(), we will override the origin() function. In afterEach(), we will restore it to its former glory.

### Mocking the class constructor.

Of the three, mocking the constructor takes a little more insight, but the activity is functionally the same. We are going to create a new class and copy all of the necessary functionality to the new class. We do this by copying over the prototype of the original point. We also need to explicitly copy over the origin() function, since class functions are not part of the prototype.

The pattern is the same. Create a copy. Redefine the function. (The constructor is just another function, just treated a little differently.) Do your tests. Restore the original definition.

I hope this clears up some of the issues around mocking JavaScript objects. This can be done easily with the language and require no additional 3rd party libraries.

# A Pox on Static Languages

It’s no secret that I am tired of .NET, C#, and static language stupidity.

My curent project went in for a code review, and I’m going to share the before snippet. This is a simple part of the project, containing no business logic — it’s just a way to check the status to make sure that the server is up.

That’s all the relevant code in this particular example. Here is the reviewers comment.

Factor all of the work out of the Status class’s constructor. Treat Status as a DTO. Put unit tests around the new factory to ensure it is properly initializing Status.

Damn. The problem with that above review is that (1) it is a lot more code to write for such a simple thing, and (2) I completely agree that’s how it should be done in C# (and probably other static languages, too). From a testing and code design point of view, the above comment represents all of the best practices that good code should follow. It keeps the result object as a plain DTO. It makes sure that the controller is responsible for nothing beyond negotiation. The reviewer’s comment is valid and accepted for work.

If I sound too put off by this, please realize that this is less than 30 minutes of work for me to do. This is much more about my distaste with the current state of static language patterns than my critique of the code reviewer.

So, let’s start by adding a factory, moving the initialization logic to the factory. We are using Ninject, so we’ll also need to be sure to register this with our IoC container.

We also need to modify our existing StatusController.

Finally, let’s modify the Status object, removing the logic from the constructor.

Finally, we need to modify our StatusControllerTests file to get all of our tests to pass. We will introduce a mock object to the controller’s constructor.

All of this is easier how? The answer, obviously, is that this isn’t easier. I’m not even convinced that it is cleaner, even if it is more clearly separating concerns.

Total changes?

• 6 files modified (Status, StatusController, StatusControllerTests, StatusTests, plus two .csproj files)
• 3 files added (IStatusFactory, StatusFactoryImpl, StatusFactoryImplTests)

Ugh.

### Reconciling with Ruby on Rails

How would I write the exact same thing in Ruby on Rails, and have the exact same level of testability (including mocking), etc.?

Wait. Doesn’t that look like the original code? Yes, it does. Thanks to Ruby’s basic attr_reader, I can quickly create the attributes for a class with very little code. The Ruby version is so much shorter because there is no reason to add extra layers (interfaces, factories) for the sake of object independence and testability in the dynamic objects world. We never require an actual type in dynamic languages, just something that conforms to the contract.

This is just another reason why I love Ruby. I can get more done faster, less typing, more clarity, and the same (or even better testability) than anything C# even comes close to accomplishing.

# The Easiest WebAPI Authorization Tutorial Ever

So, it took a lot of scouring of the internets, but I was finally able to piece together the bare minimum necessary to create your own authoritization client in WebAPI.

### Step 1: Create a DelegatingHandler

The DelegatingHandler is a class that will be attached to all requests coming into your API. This is going to be the easiest authorization handler ever. Here are the rules.

1. If there is a token, any token at all, the request is valid.
2. Otherwise, the request is unauthorized.

Yes, this is simple. In reality, you’d want to check the value of the token against something, at the very least a local database. That is left as an exercise for the reader.

### Step 2: Wire Your Handler to Your Configuration

Somewhere, you probably have a class that sets up your WebAPI configuration. You need to add this line to your configuration.

### Step 3: Add an Authorization Header to Your Requests

For this to work, you’ll need to add an authorization header to all of your requests. It needs to be in the following format.

Here’s a sample. (No don’t actually use this token. It’s just the SHA256 hash of Hello, World!.)

### Step 4: Test With and Without an Authorization Header

Fire up Fiddler. Let’s create a request without an authorization header.

The request.

The reponse. We can see the 401 Unauthorized coming back from the server.

Now, let’s look at the same request with an authorization header.

The response. Now with more 200 OK.

We’re successfully grabbing the token from the request. Everything else is left as an exercise for the reader!

# Unit Testing an MVC Authorize Attribute

When working with unit tests, I usually consider it a code smell when you have more fixture setup than production code. Today, I ran into just that condition.

This class has been written for a while, but it wasn’t covered by any tests. I decided to change that. First, I’ll show you the class. The class under question is called SessionBasedAuthorizeAttribute. It looks to the ASP.NET session to get the username, instead of relying on a forms token.

Writing your own AuthorizeAttibute isn’t difficult. It’s just a few lines, really, to pull a value from session, fetch a user from the database, and set the user. But what about unit testing?

By the way, there’s even more setup code that happens as a part of the MvcTest.SetupControllerContext() method call, but I had already written that for another purpose.

### 13 lines of production code. 25 lines of fixture setup.

It turns out, that’s much more difficult, because we are relying on a lot of the inner guts of MVC. I had to pull up the source code for the OnAuthorize method to see what all the NullReferenceExceptions were. When mocking out the HttpContext, you also have to mock out the Session (knew that) and Items (didn’t know that) properties. There are also some ActionDescriptor values that must be set for OnAuthorize to work, and I have never worked with those classes before, either.

I suppose the first conclusion is to praise the powers at Microsoft for open sourcing the MVC framework. Without access to the source, I would have never been able to write these tests. Even with the source, the terrible nature of the NullReferenceException made this much more difficult than it ought to be. Any time you have a chain of w.x.y.z, finding which of those threw the exception becomes a total PITA. Yeah, I know. The Law of Demeter is in play, too.

Check out Code Contracts. It makes this kind of in-code documentation much easier.

The second conclusion is the value of this kind of test. I’ve already had one coworker respond with, “this is where I begin to question the value add of unit testing.” I kinda have to agree with him. This was a hard test to write, even though the production code itself was quite easy. On one extreme, some people say that if it is important enough to write, then it is important enough to test. I think I agree with that sentiment. I believe in the value of testing. I’m just not sure what I could have done to make this testing easier and still remain within the bounds set by the MVC framework.

# BCrypt Is Slow

For some reason, this just made my day.

See those yellow dots? That’s NCrunch telling me that these tests are slow. It’s BCrypt. It’s supposed to be slow! That’s the whole point of using BCrypt. If you’re storing passwords, it’s the only hashing algorithm you should be using.

# JavaScript Objects

This is always a good topic to review. There are just too many developers who don’t know what they are doing when it comes to writing good JavaScript. The code for this project has been published to Github.

### Understanding Scope

The first thing we must understand is how variables are scoped in JavaScript. When it comes to JS: there’s only one rule.

Variables are scoped to the function that defines them.

There’s no concept of block scope like in C# or Java. This means that we’re going to make use of something called a functional closure.

### The Specs

Specs are a wonderful way of defining how a class should work. Don’t tell me this is BDUF or not how TDD is supposed to work. Both of these methodologies would say to only write one test, then write the code. Repeat until you are finished. This is why I refuse to strictly follow a dogma. If you know the specs up front, then write the specs.

The following tests are written with the Jasmine unit testing framework.

### Declaring the Constructor

Yes, we had to type the name of the class three times and the word function twice. I’m sorry.

### The Functional Closure

The above code example is a functional closure. The more you work with good JavaScript, the more you’ll see this pattern. Yes, it’s a lot of character noise. I’m sorry Ruby developers.

The above line creates an anonymous function that is executed immediately. In this example, we are creating a new Speaker function and then returning that function. The functional closure will let us hide variables that we don’t want exposed outside of class.

This will let us create new instances of our Speaker class.

### Objects Are Instances of Functions

What syntax makes function Speaker() any different from function speaker()? Nothing at all. The only reason that we are capitalizing Speaker is by convention of those who have come before us.

### Adding Properties

We also think our speaker should have a name. I like to know to whom I am speaking.

We can now test that the speaker really does have a name attribute now.

### Constructor Options

We should get used to using an options object in our JavaScript. Instead of having an explicit list of arguments, we instead accept a single options object as a method parameter. Remembering that JavaScript does not have a compiler, this allows us to be very clear about the expected inputs to our methods.

Having an options parameter also lets us set some defaults. Both jQuery and Underscore have an extend method that let us map settings. They both do the exact same thing. For no particular reason, I’m choosing Underscore over jQuery.

So, by default, our speaker will be named “Ann,” but we can still change it by adding a name attribute to our options argument.

Also, notice that the defaults are private to the functional closure. There is no way to access these defaults from outside the Speaker object. While we can access speaker.options.name, we cannot, in any way, access speaker.defaults.

### Adding a Functional Prototype

To expose a public function, we need to use the prototype attribute.

### Duck Typing

I’m not going to get into duck typing today. A lot has already been said by developers much smarter than I. Check out Eric Lippert’s post and Phil Haack’s first and second posts. Instead, here’s the short, short version…

I’m going to call something - a method or property - and you had better just “work.”

That’s all we are going to do with the output buffer in this case. I’m going to call a .write() method. I don’t care what you give me, but I’m going to call that method.

We’re going to go back to our constructor here.

• AlertBuffer: Writes to window.alert.
• ConsoleBuffer: Writes to console.log.
• MemoryBuffer: Writes to an internal array.

I wrote all three versions. They are available in the repository linked above. Here’s the code for the MemoryBuffer.

We’ll set our buffer in the constructor of Speaker. We’ll go ahead and default to the MemoryBuffer. If you want the MemoryBuffer, then leave it alone. If not, then give us a new buffer when you create your Speaker instance.

### Creating a Private Function

Now we want to create a private function. This function needs to be exposed to the Speaker instance, but not outside of the instance. We can’t use a prototype for this, so how do we accomplish this? Answer: we just create a method inside of the function. This will scope it locally, preventing it from being exposed.

With that, we will now pass all of our specs.

# Relying on Unreliable IDs

Relying on IDs means that we are checking that a value set by the database. This may be an autoincrementing value — a SQL Server identity or an Oracle sequence.

### Why This Happens?

This anti-pattern occurs because it is thought to be easier to hard code values into the software than to make changes to the database schema. When the schema is wrong, fix it!

### Example: Include/Exclude by Value

In this case, this particular department is a virtual department, not a real department, and we don’t want it displayed in this particular UI screen.

However, in this program, the ID column is a SQL Server identity. The value of 6 was assigned to the row in the developer’s environment. However, there are three more environments to consider: QA, Staging, and Production.

There are two anti-patterns to this approach.

1. It assumes that data will be entered in the exact same order. It also assumes that if there was a mistake before, the mistake would be repeated, since a failed insert will increment the identity.
2. It assumes there will never be another department that we wish to exclude.

#### Solution: alter the schema to reflect the intent

The solution is to alter the database to reflect this logic.

The application code is now extremely easy to understand, and there is no reliance on “magic” values.

### Example: Setting a Default Value

In this example, we are using a value to reflect that something should have a default setting.

Again, this assumes that the “new” status will always be present. If you, ask the developer have complete control over the environments and deployments, then this does work. Also, you’re luckier than I, since I have never been at a client where I have complete control over deployments.

#### Solution: alter the schema to reflect the intent

The application code is similarly trivial.

Now, whether the query for .IsDefault should be a call to .First() or .Single() is an argument I don’t really want to get into. Ideally, it is probably correct that only one value can ever be the default value. However, I’ve been places where I don’t have any control over those particular administration screens, and the code quality is rather dubious. In that case, I chose the .First() method because I didn’t want my code to break because of another developer’s poor decisions.

Yes, I realize my code will still break if there are no default statuses. The [status_id] column in the database is not nullable, so .FirstOrDefault() is just prolonging the issue.

Lesson Learned: Don’t rely on magic.