Item Templates in Visual Studio 2015
Now that blog posts, metadata, and comments are combined in one file, it's less work to start a new post. I figured I'd reduce friction even further by using a Visual Studio Item Template. It's best to remove every barrier to writing new posts. ;-)
I found a nice article on Visual Studio templates by Eric Sowell which answered the basic questions and another about multiple file templates that happened to get me past a stumbling block when editing a template.
Mostly everything is the same as in those posts, except the directories are different for the newer version of Visual Studio. There are a couple of caveats when doing a template for a file that doesn't end in .cs
. To make it easier to see what I'm doing, I also made a companion video.
To Catch a Bot, Use a Honeypot
For my contact form, I needed some spam protection from the evil bots roaming the interwebs. I considered recaptcha, but I want to minimize the amount of javascript on this site, plus it's fun to see what I can do on my own.
For inspiration, I remembered a post I read long ago from Sam Saffron on blog spam. In it, he talks about the habits of bots and how they love to fill out form fields. The trick then is to give the bots something to fill out that humans won't. Instead of making humans prove they are not bots, make bots prove they are human.
I recently used formspree which has a _gotcha
field for this purpose. I added a similar field to my contact form and hid it using css, so humans won't be bothered by it. The results were great. The first contact that came in was marked as a bot!
Let's Encrypt, Shall We?
TLS Everywhere is gaining traction. I'm not convinced, but I'm not passionate enough about the issue to dig into it. I was intrigued by the Let's Encypt project and it's mission to provide free, pervasive, SSL Certs, and wanted to see if I could get it working IRL.
Troy Hunt has a good post on setting up Let's Encrypt on an Azure WebApp. [Side note, Troy has a lot of great articles on his site].
The most painful part of this process was setting up the principal in Active Directory. Dealing with AD always makes my heart sink. There are so many terms and concepts that I have zero interest in learning.
Setting Up Azure CDN
Using a CDN is a well known way to increase the performance of your web site. At $0.087 per GB, I figured why not give the Azure CDN a try.
My first concern was I didn't want to have to push assets, especially css, to the CDN as a separate step in my release process. I found a decent guide on setting up origin pull for the Azure CDN. That post shows the old portal. The process in the new portal is a bit nicer, but the concepts are the same.
I did run into a couple of issues which may help you out.
Comments Collapse
At the end of my previous post, I considered merging the comments into post file.
I couldn't help myself. ;-)
With a little C# interactive, I now have half the files. Here's the code I typed into the interactive window:
#Winning with C# Interactive
For my blog engine, I had a static C# class that contained a list of metadata about each post. That means when adding a new post, I had to add an element to the Posts list and create the markdown file.
Instead, I've decided to keep the post metadata in the file itself. For the format, I followed the Jekyll Front Matter convention.
I was facing the tedious task of typing all the metadata in the posts when I remembered that VS 2015 comes with C# Interactive.
Removing Disqus with F#
In my previous post, I wrote about removing Disqus from this blog. One tricky part was dealing with the comment export data. While you certainly can get your comments out of Disqus, they don't come in a great format. You get a lovely chunk of xml where the posts (called threads) are disconnected from the comments (which are called posts).
I needed something that would let me parse the data without too much effort. This code only needed to be run (successfully) one time. I considered using the C# xml classes or doing something dynamic, but I wasn't thrilled at the prospect.
It turns out, FSharp.Data has an xml type provider. It also turns out that F# type providers are amazing.
Goodbye Disqus
I've decided to remove disqus comments from my blog.
I had several issues with disqus:
- Long page loads [async aside]
- Threaded comments
- Time shifting - oldest may not be on top, so a "first!" comment might be in the middle
- Links to other sites
- Injected marketing cookies
What really forced the decision was the nature of comments themselves. Are comments a valuable part of the blog? If so, I should own them. If not, I should turn them off.
Asp.net MVC Content Negotiation
It's long bothered me that I had a separate endpoint for Atom. After adding the archive endpoint, the absurdity really showed since is the same data, just in a different format.
Content negotiation to the rescue.
Web API has a decent conneg system built in. Fortunately, asp.net has enough extension points that we can craft a workable solution.
A Tale of Scope Creep
Zach Burke mentioned to me that he wanted to add a 404 page to his new blog. Sounds like a good idea, lets do it.
I assumed I was going to configure httpErrors, but I figured I'd google a bit anyway. Turns out, there is quite a debate about 404 pages with asp.net mvc. I decided I didn't really care about the nuances and I wanted to get the feature done. Good enough. Commit.
Next I decided that the 404 page should display the post archive so that the user can choose a post that exists. Hmmm. Ok, a little scope creep: how about we have an independent archive page. Fine. Using the mediator, it was straight forward to implement. Commmit.
Vessel Modules
After implementing Vessel, I was curious what it would be like to add a module system. To do this, I added a RegisterModules method that scans for classes implementing IModule
and executes them.
Doing this allows us to define our mediator functionality in context. I like this because it allows us to add new features without having to modify a central registry.
The down side is we lose some Application level legibility. We are exchanging that for Feature level legibility. Vessel allows us to arrange your projects as we see fit.
Introducing Vessel
Sorry to frighten you on this Hallow's eve, but this post is not about yet another mediator. :-]
After finishing Liaison, I found myself coding in anger. What else could I cull from my stack? The obvious answer:
Kill the IoC Container.
Introducing Liaison
Well nimbus, you had a great run, but now it's over. Make room for Liaison.
While I was building nimbus, something was nagging me. It was great and flexible and web scale and all, but...
Nimbus is utter bloatware!
Introducing Nimbus
Once I started questioning IoC containers, a variety of problems presented themselves.
Near the end of questioning IoC, I posited an escape hatch:
new Mediator(new DoThis(), new DoThat(), new DoTheOther());
Working to achieve this api, I came up with Nimbus. To see how it works, I incorporated nimbus into this blog.
Creating a ReSharper Macro
I wanted to get R# to do a little typing for me so that I can more easily add new blog posts.
A new post looks like this:
new Post
{
Title = "Creating a ReSharper Macro",
Slug = "creating-a-resharper-macro",
FileName = "creating-a-resharper-macro.markdown",
PublishedAtCst = DateTime.Parse("October 17, 2013"),
},
The slug and filename are independently adjustable for flexibility, but they usually start out as a derivative of whatever I'm going to name the post.
Constructor Injection is Partial Application
Looking back on my posts about violating ISP and duck typing, a question emerges: why not declare our dependencies on the methods that need them, rather than at the object level?
For example:
void LoginUser(IAuthenication auth, string userid)
This code would be very explicit and allow us to be more granular with our dependency chain.
Interface Inversion
On my previous post, Joey Guerra asked a question in the comments:
Can we go further? Can't we just say that class Oauth2Authentication is the interface? I mean, why do I have to care if it implements IAuthenticate? Do I care if it implements that "interface" or do I care if it has or doesn't a method called Authenticate?
In other words, isn't the interface declared in the wrong place?
Foo: IFoo is an Anti-Pattern
This simple code, used in so many examples, has always bothered me.
class Foo : IFoo
The idea is that we have abstracted an interface so we can be solid and our IoC container will even make this easier. We must be on the right path. Right?
Wrong.
How to Wake Up Your Kids
Ever think that your young kids are sleeping too much at night or during naps? Feel that you aren't spending enough "bonding time" with them because they just sleep sleep sleep?
Here are a few tips to wake up your kids based on personal observation.
Lay your head down and close your eyes.
Violating SRP with Constructor Injection
In the previous post post, we explored how constructor injection can be abused to violate isp. At the end, I mentioned possible SRP violations as well.
Let's look at the same class:
public class CustomerService : ICustomerService
{
private readonly IRepository<Customer> _repository;
private readonly IEmailService _email;
public CustomerService(IRepository<Customer> repository, IEmailService email)
{
_repository = repository;
_email = email;
}
...
public void CreateCustomer(Customer customer)
{
_repository.Add(customer);
_email.SendWelcomeEmail(customer);
}
}
CreateCustomer
calls the repository to add the customer and instructs the email service to send the welcome email.
Violating ISP with Constructor Injection
One problem with IoC containers is that they facilitate ISP violations through constructor injection.
The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.
Let's take a look at some typical, and very terrible, code. I'm actually astonished at how many anti-patterns can be put into so few lines of code (AP/LOC?). It makes my eyes bleed.
Questioning IoC Containers
Last night I awoke at 3am with a thought: maybe Greg Young has a point.
The other day, I watched Greg's 8 lines of code video. I found myself agreeing, out loud, with the presentation, which is somewhat startling when you're sitting by yourself. One thing I couldn't quite swallow was his "no ioc" stance.
But then, I woke up with that thought.
.Net Demon
Sometimes it's the little things.
A while ago, I installed .net demon and ran the trial. I was instantly impressed.
The trial expired during a period when I wasn't coding at home very often. I kind of forgot about it, except for occasionally noticing the trial expiration reminder at the bottom of visual studio. Too many other more pressing things to do...blah blah blah.
Learning NServiceBus Review
I was contacted by Packt Publishing to review Learning NServiceBus by David Boike. David is active in the NServiceBus community, so I was eager to see what he had put together.
Using a messaging framework can be a daunting prospect for someone who is used to typical RPC / web service programming. In Learning NServiceBus, David has distilled the essential parts of getting messaging to work on NServiceBus into easily digestible bits. I consider myself a slow reader yet I was able to get through the book in a few hours. Also, as someone who is familiar with NServiceBus, I thought I might find the material boring. Instead, David presents it in a fun, engaging manner that had me happily swiping through the pages [kindle reader on iPad].
Building My Own Blog
Why not? I took a day and wrote a blog engine. I had a few goals in mind. I started by stealing, er, uh, learning from the blog of Tim G Thomas whose source code is conveniently on GitHub.
Minimalism
I didn't go bare minimum, but I feel like I got pretty close.
- No javascript.
- No DB.
- A minimal css framework called Kube.
- CSS icons from Font Awesome.
- Markdown for posts (like this one).
I cheated a bit. I didn't want a db, but I figured a blog has to have comments, so I went with Disqus. So, technically, Disqus has a db on my behalf and loads through js. But those things aren't in my code base which means I don't have to maintain them. Win.
Javascript UTC Datetime
I created a date in js like this: new Date(2012, 0, 1, 8, 15, 0);
.
When I console.log it, I get this: 2012-01-01T14:15:00.000Z
(My timezone is CST).
The date is already converted to UTC and will convert back to local time for display. If you ship the date to js as UTC, it just works.
Just use string Id for RavenDB
I tried to fight the framework, but it isn't worth it. With RavenDB, the default expectation is to use string for Id properties and they will get generated to look like this: "posts/1". The slash causes a problem for MVC routing and it doesn't look all that great "posts/details/posts/1".
You can overcome the MVC issues pretty quickly just by making your Id an int property. Blam. It works and your route looks like "posts/details/1".
It turns out though that once you get into more interesting RavenDB features, notably indexes, using int for Id is a real PITA. Indexes run on the Server and the server still sees all the document as having Id as string list "posts/1". Your queries with int Id properties won't match and you'll be frustrated.
Seeking Density in Architectural Abstractions
I've found myself making mental leaps about coding more quickly by cross pollinating the input data.
Take architectural abstractions. They've always grated on me. The better I got at writing code, the more I thought they were a waste of time...most of the time.
Yesterday I was reading the latest in a series of Ayende posts about Limiting your abstractions.
FubuMVC, Validation, and Re-Hydrating the View
Last week, I started experimenting with FubuMVC. About two months ago, I met three of the Fubu guys down in Austin and they sparked my curiosity about FubuMVC. Last month I took Udi Dahan’s excellent SOA course and asked him about FubuMVC in light of his views on SOA. His response was to challenge me to give FubuMVC a try and find out.
I started working my way through the beginner material on FubuMVC when I struck upon an issue present in any web framework: when you POST data and hit a problem, how do you re-hydrate the view with the data the user entered and show the user about what went wrong.
I recently came up with a solution that I was happy with in ASP.Net MVC3. However, the solution relied on a base class and FubuMVC steers us toward a compositional approach to development. I ran across these stack posts and they meshed very well with my solution for ASP.Net MVC3.
Selling Value for Money
One recurrent theme in business is the disconnect between the “product team” and the Sales/Marketing team. I’ve repeatedly seen product teams working long hours to make insane deadlines because the Sales team has undersold their value.
Sane rules of sales go out the window when it comes to selling software, and probably any kind of service business that primarily involves brain work like advertising or design.
The salesperson goes out and makes a deal in which the customer gets 100 hours worth of value for 40 hours worth of dollars. The salesperson celebrates another successful closing and moves on.
NullOr Extension Method
I find myself writing code like this a lot:
public static void DoSomething(Foo foo)
{
var thing = foo == null ? null : foo.Thing;
}
I thought about adding an operator like ??? to go with ?? and ?, but you can’t do that in c# and it would probably be confusing to the next programmer anyway.
So how about an extension method to wrap that up:
Null Check with Extension Methods
I mentioned that I got an idea while writing the post on extension methods. I realized that you can null check using this technique.
It get’s annoying writing this code over and over:
public static void ImportantMethod(string value)
{
if (value == null)
throw new ArgumentNullException();
}
I had considered using a NotNull<T>
to take care of null checking.
Avoiding Negative Branching Tests
I try to avoid ! tests in “if” blocks if there is a clearer way to express the idea in positive manner. Thanks to Larry McNutt for turning me on to this concept.
In my post on extension methods, I had a string extension called HasValue. What’s the use of this?
//negative logic:
if (!string.IsNullOrWhiteSpace(s))
return;
//becomes:
if (s.HasValue())
return;
I think the second form is much more readable in that you have one less “twist” to think about.
Cool Feature of Extension Methods
One cool and useful feature of extension methods is the fact that a null instance can call the method.
So say you write some code like this:
using System;
namespace FizzBuzz
{
public class ExtensionsDemo
{
public static void TestString()
{
var s = "hello";
var ok = s.HasValue();
s = null;
ok = s.HasValue();
}
}
public static class StringExtensionMethods
{
public static bool HasValue(this string value)
{
return !string.IsNullOrWhiteSpace(value);
}
}
}
You would expect the second call to HasValue would blow up because the string is null. But the extension method is on the class not the instance so it goes through with no problem. Very handy. In fact, while typing this post I just thought of a very good use for this…coming soon.
Visual Studio Code Snippets
I’m still crying over this. Just go in VS2008, type “for”, and hit tab twice. The try alt-K, alt-X and pick anything under the c# menu.
If you knew this before and didn’t tell me, you’re probably the same person who laughed while I manually typed out using directives.
Switch on the code has a code snippet tutorial.
Quickly Creating Using Namespace Directives
If you’re not watching TekPub videos, you’re doing yourself a disservice.
I was watching an awesome video from the Mastering ASP.NET MVC 2 series, and i noticed the presenter doing something interesting.
I haven’t been too big on visual studio shortcut keys, so when I saw this it just made me cringe. If you type a class name that you don’t have a using statement for, but Visual Studio knows about the class, it will suggest using directives to you and allow you to easily add them to the using directive section at the top of the class file.
Thoughts on Script#
I had an email discussion about Script# the other day. I didn’t like it. I admit I looked at the website for less time than it took me to write this post.
After sleeping on it, I figured out what bothers me about it. It reminds me of WebForms – let’s pretend we’re not in a browser.
Better approaches to being uncomfortable working in a browser:
In Defense of Blub
A while back, I read quite a bit of Reginald Braithwaite’s excellent blog. If you care at all about programming, reading his blog will intrigue, mystify, depress, and inspire you.
I particularly liked his post about everyone being a Blub programmer. To quote a Paul Graham quote from Reg’s blog:
Blub falls right in the middle of the abstractness continuum… As long as our hypothetical Blub programmer is looking down the power continuum, he knows he’s looking down. Languages less powerful than Blub are obviously less powerful, because they’re missing some feature he’s used to. But when our hypothetical Blub programmer looks in the other direction, up the power continuum, he doesn’t realize he’s looking up. What he sees are merely weird languages… Blub is good enough for him, because he thinks in Blub.
Why Enums Suck
I inherited some code at work that made use of enums. I happily continued the pattern in order to get the job done considering the tight deadline. My spidey sense kept tingling telling me something was wrong, but I couldn’t quite put my finger on it.
The code I started with was pretty standard stuff.
There was an enum:
Avoiding FizzBuzz
Getting hired for a programming job means interviewing. This process is utterly necessary, but often tedious.
Interviewers have to be able to weed out the “no hopers”. The problem is, decent candidates are put off being asked “the basics”.
For me, the problem is time. We only have 45 minutes to an hour for the interview. I’d rather spend the time talking about our respective views on SOLID, Agile, IoC/DI, CI, etc. The really important point of an interview is determining whether there is a "fit" between myself and the company.
FizzBuzz++
Thanks to Matt Taylor sending me email comments about my Avoiding FizzBuzz post, I decided to jazz it up a bit.
This whole blog is dedicated to avoiding FizzBuzz type questions in general, so I figure the more code posts the better.
Using my IEnumerable Each extension method, I tried out this version of FizzBuzz:
IEnumerable Each()
I’ve wanted to write an each statement for IEnumerable for a while, but haven’t bothered, mostly because other devs had decided to translate everything to List anyway so I just used .ForEach or a straight foreach as appropriate. A comment on my Avoiding FizzBuzz post by Matt Taylor spurred me to do an implementation.
Anyway, an Each() extension method on IEnumerable is trivial:
public static class IEnumerableExtensionMethods
{
public static void Each<T>(
this IEnumerable<T> list
, Action<T> action)
{
foreach (var item in list)
action(item);
}
}
Gmail’s Spam Criteria is Stringent
Gmail doesn’t mess around with spam. Even messages from Gmail are not above suspicion.
TekPub Rocks!
I finally got around to getting a subscription for TekPub. I watched three of the jQuery videos, two of the MVC videos and one Linq video.
The thing is, I use jQuery and Linq all the time. I thought I “knew” these technologies. I’ve watched a slew of the MVC videos on asp.net. I’ve read articles all over the web. I’ve read the docs for these products.
I learned more in these six videos in a day than I had in a year of fumbling around. The problem is that you have a project to get done. With jQuery, things were so much easier than writing raw js, I thought it was great already. I see now that I was missing quite a bit. For Linq, I got the clearest explanation of how we moved from .net 2.0 to 3.5, exactly what lambdas and delegates do and how they are constructed essentially. I was decent at using Linq, but I always found myself struggling to explain it. Now I can say – Goto TekPub.