Adam
This user hasn't shared any biographical information
Posts by Adam
Sublime Text 2/Textmate port of studiostyl.es “Son of Obsidian” theme for Visual Studio
Feb 15th
I’ve been a fan of the popular Son of Obsidian theme for Visual Studio since it came out a couple of years ago. However, I’ve found myself using Sublime Text 2 more and more because it’s lightweight, fast and has some great features that almost make it full like a full IDE without the bulk. However, I missed my Son of Obsidian theme, so awhile back I decided to port the theme and create a Sublime/Textmate compatible version.
You can find it on GitHub here.
If you have any changes, please feel free to fork it and contribute.
Enjoy!
Why Microsoft Developers Should Care About Node.js
Jul 6th
I’ve been a Microsoft developer since I started programming straight out of college and I know there are many others out there just like me. It’s been a comfortable space that has been growing steadily over the past 10+ years. However, in the last 3-5 years or so, I branched out of my Microsoft comfort zone and dipped my toes into other languages, platforms and frameworks such as iOS development, Android, Ruby on Rails, PHP and most recently Node.js.
There’s been a lot of debate since Node’s arrival as to whether or not this is a step backwards for software development. JavaScript on the server? You mean the almost 20-year-old scripting language that I’m still using on the client but only because jQuery makes it look easy? Yes, that JavaScript!
Likewise, if you came from a Classic ASP development background like me, then you probably knew that with Classic ASP, you usually had 2 languages to pick from: VBScript (the most common) and JScript (Microsoft’s Implementation of ECMAScript). Other languages such as PerlScript, Python and others could also be installed via third-party Active Scripting Engines, but the two main ones that came built-in were VBScript and JScript/JavaScript.
While most folks (myself included) used VBScript for Classic ASP development, JScript (JavaScript) was (and still is) an interesting option. It’s dynamic like VBScript, but more structured and case-sensitive like C#. Personally, I always liked JavaScript because of this blend between it’s dynamic nature and it’s structured C roots. If you’re in a corporate Microsoft-shop environment like I was up until a year and a half ago, you may still find yourself maintaining some legacy Classic ASP systems. If so, I encourage you to experiment with JavaScript and Classic ASP. It will prepare you for getting used to JavaScript on the server with Node.js. If you’re strictly a .NET developer, think a maleable C# without so many rules. To use JavaScript for Classic ASP, you simply add the following language directive to the top of your .asp files:
<%@ language="javascript"%>
And then you can do something like:
<%
// CustomerRepository class
var CustomerRepository = function() {
this.save = function(customer) {
// insert/update in db
};
this.findById = function(id) {
// retrieve from db by id
};
this.delete = function(id) {
// delete from db by id
};
};
var customerRepository = new CustomerRepository();
// In Classic ASP or other programming languages, this would block the current thread until the database returned the customer
var customer = customerRepository.findById(12345);
%>
If you’re a C# developer, this probably looks very familiar. It’s not statically-typed like C#, but the syntax is familiar and that last line looks almost identical to passing an anonymous type in C#.
Now, as far as Node.js goes, this same “class” could be made into a simple Node.js module with some minor changes:
- First, we’d remove the angle-bracket percent (<%%>) tags
- Next, we’d rename the file to CustomerRepository.js and export this as a module
- Finally, using Node’s callback convention, we’d add a callback parameter to our methods like below. Or, we could use an event-driven approach by inheriting from Node’s EventEmitter.
Then, we’d end up with:
// CustomerRepository class
var CustomerRepository = function() {
this.save = function(customer, callback) {
// insert/update in db
};
this.findById = function(id, callback) {
// in a real app, we'd kick off some I/O and retrieve the customer from
// a database, web service or somewhere else
// since this isn't a real app, we need to throw this on the event loop/queue
// so as not to block the current thread. We do that using process.nextTick
// if I hadn't wrapped this in process.nextTick, then this would actually
// fire immediately which would block Node's main thread which is a
// bad thing since there's only one of them!!!
process.nextTick(function() {
callback({ id:123456, name:'Joe Customer', email:'joe@somewhere.com' });
});
};
this.delete = function(id, callback) {
// delete from db by id
};
};
module.exports = new CustomerRepository();
Using Node’s require statement (akin to include in Classic ASP or using in C#), we could then import this module like so:
var customerRepository = require('./lib/CustomerRepository.js');
// In Node.js this will not block the current thread since this is an I/O operation
customerRepository.findById(12345, function(err, customer){
if (err) {
console.log('Oh no, something bad happened: ' + err);
} else {
console.log('Yippee! We got a customer back: ' + customer.name);
// now, do something with the customer object
}
});
Nothing revolutionary here. My point is to simply show you that there is nothing inherently magical or complicated about JavaScript on the server. It’s still the same JavaScript you use on the client today with libraries like jQuery etc. and the same JavaScript you could have used with Classic ASP 15 years ago.
However, the part that does make JavaScript magical on the server is Node. It’s built on top of Google Chrome’s V8 JavaScript Engine. Yes, Google Chrome – the superfast browser that you’re probably using to read this (unless you’re locked into some corporate standard of using Internet Explorer
). For those of you that are using Chrome, you know how fast Google Chrome is. Well, V8 is the magic behind Chrome’s speed performance when it comes to JavaScript.
What Node does is bring that speed and performance to the server in the form of a fast, lightweight, single-threaded event loop. Wait! Hold Up! Did you say “single-threaded?” Yes, I said “single-threaded.” Rather than spawn new threads or use a pool of worker threads to service new requests, Node takes a different approach to performance in the form of a non-blocking evented model that is designed to be asynchronous. This is good for developers because it means we don’t have to worry about thread pool management, sync locks, mutexes, race conditions and the joy (sarcasm) that is debugging multi-threaded programs. However, in order for Node to allow a single thread to handle multiple concurrent requests, you can never allow the main thread to wait on blocking, synchronous or CPU-bound operations. Note the phrase “you can never allow” in the previous sentence. Node will not prevent you from writing blocking, synchronous or high CPU-bound operations. Node will handle making I/O operations non-blocking for you, but for anything else, It is your responsibility as the developer to make sure you are writing non-blocking, asynchronous code. Node simply gives you the framework and conventions for doing so, but it does not mandate this. You read more about how Node works here.
Still, you may be asking, why JavaScript on the server? Well, if you’re doing web development these days you are probably using JavaScript on the client for things like form validation, DOM manipulation, ajax, lazy content-loading, etc. If you’re working with web services, you have probably consumed JSON through an API like Twitter, Facebook or maybe you’ve rolled your own. So, you’re using JavaScript on the client. JavaScript in transport (in the form of JSON) and you may even be storing some JSON on the server whether as serialized data in a relational-database such as SQL Server, Oracle, MySQL or PostGres. Or, maybe you’re using a NoSQL database such as MongoDB, CouchDB or even Azure Table Storage.
So, if you’re using JavaScript on the client, JavaScript in-transport and JavaScript for persistence. It only begs the question, should JavaScript be used on the server?
Node’s answer is “yes” and many developers have come to that same conclusion (end-to-end JavaScript) and that is why Node.js has gone from an obscure project just a few short years ago to one of the most actively followed projects on GitHub today.
Now, we get to the part of why you should care about Node.js as a Microsoft / .NET developer.
Microsoft has taken notice of Node’s growing popularity and its merits and they have worked with the Node.js community on Windows support for node and IIS support through iisnode. Microsoft has embraced Node.js as a first-class citizen in Windows Azure, going from MIA a little over a year ago to being listed as the first language (below .NET) on their Window Azure Developer Center, ahead of Java, PHP and Python.
Node.js on Azure is actually a great story that has many benefits aside from running Node yourself.
As this article points out, Microsoft doesn’t adopt outside technologies that aren’t established. Just like their official support for jQuery, Microsoft’s support of Node.js signifies a shift from “cool fringe technology that carries too much risk to use on a real project” to “something I should at least start becoming familiar with in case it becomes the next jQuery.”
Despite this, you may be asking yourself, “is JavaScript-development the direction I want to take my career,” look no further than Windows 8 and its support for building Metro apps with HTML5, CSS and…..JavaScript. I would submit that just like writing Classic ASP with JavaScript wouldn’t make you any less of a Microsoft developer 15 years ago, writing Node.js apps with JavaScript won’t make you any less of a Microsoft developer today. JavaScript is here to stay. If you don’t like the language or its syntax, then take a look at CoffeeScript, a little syntactic sugar over JavaScript.
Who knows, your next project might be an HTML5, CSS and Javascript Windows 8 Metro App that communicates with a Node.js server running on Windows Azure backed by MongoDb. Sneak in a little javascript into that Classic ASP app you’re still supporting 12 years later and you’ll feel right at home.
If you’re a Microsoft developer, let me know what you think of Node.js in the comments.
Happy JavaScripting!
Status of SimpleMembership.Mvc3 and SimpleMembership.Mvc3.Sample
Mar 9th
I have received a couple of questions and requests over the past 6 months or so regarding my plans to update both the SimpleMembership.Mvc3 and SimpleMembership.Mvc3.Sample packages.
In short, I’m planning on updating these but I just haven’t gotten to it yet. I’ve been very busy lately with some other projects such as Expansive and my C# wrapper for the DNSimple REST API.
However, in preparation for these changes I have started a Trello board here: https://trello.com/board/simplemembership/4f23419c0fa7e50d34585d9e
I’m using this to track requests I have received and to communicate the status of the features that have been requested.
Please feel free to comment on them or vote or request new features.
However, these being open source projects on GitHub, please also feel free to fork them, add your desired features and submit a pull request to me to merge your changes back into the trunk.
Both projects can be found on GitHub using the following links:
- https://github.com/anderly/SimpleMembership.Mvc3
- https://github.com/anderly/SimpleMembership.Mvc3.Sample
I am going to try to get these changes done soon, but I just haven’t been able to dedicate any time to them yet.
In the meantime, thanks again for your interest, feedback, questions and requests regarding SimpleMembership.
Stay tuned…
Expansive 1.5 Released
Oct 14th
Yesterday, I blogged about my new .NET string expansion library called Expansive.
Today, I made some key changes to, hopefully, make it easier to use and more flexible by providing 4 token style format providers out of the box.
- Removed the startToken and endToken delimiters that could be set by the consumer as this was unreliable
- Added 4 new Token Style Formats to pick from:
- MvcRoute Style “{token}” (default)
- Razor Style “@token” or “@(token)”
- NAnt Style “${token}”
- MSBuild Style “$(token)”
So, the following are all valid:
// MvcRoute-Style (default)
var mvcRouteStyleString = "Hello, {FirstName}".Expand(new { FirstName = "John" });
// Razor-Style
Expansive.DefaultTokenStyle = TokenStyle.Razor;
var razorStyleString = "Hello, @FirstName".Expand(new { FirstName = "John" });
// NAnt-Style
Expansive.DefaultTokenStyle = TokenStyle.NAnt;
var nantStyleString = "Hello, ${FirstName}".Expand(new { FirstName = "John" });
// MSBuild-Style
Expansive.DefaultTokenStyle = TokenStyle.MSBuild;
var msBuildStyleString = "Hello, $(FirstName)".Expand(new { FirstName = "John" });
// all return "Hello, John"
You can also specify the TokenStyle on the call to Expand() such as:
var expandedString = "Hello, @FirstName".Expand(new { FirstName = "John" }, TokenStyle.Razor);
The addition of TokenStyle makes the API a little cleaner and provide 4 popular token formats.
You can of course add your own by grabbing the source on GitHub and opening the hood.
Enjoy!
Expansive – A powerful string expansion library for .NET you never knew you always wanted.
Oct 13th
Expansive
- having a capacity or tendency to expand.
- causing or tending to cause expansion
- characterized by richness, abundance or magnificence
While working on a recent project involving lots of appSettings keys and values in my web.config/app.config files and some values that have overlapping information (server names, file paths, etc.), I realized how much I missed the property expansion capabilities of NAnt and, more recently, MSBuild. So, I set out to see if I could quickly build a simple string property expansion library to solve this common problem and maybe some others along the way.
While I knew that true string interpolation would be somewhat tricky and probably best left to the framework developers, I felt that an easy add-on API using extension methods and possibly some new helper classes could at least make my life easier.
Channeling Rob Conery, I named my new library Expansive as a play on Expansion and Expensive (sarcasm) as I wanted something that wasn’t expensive (technically) and was easy to implement and easy to learn.
You can check out the full capabilities via the readme over on GitHub, but I’ll give you a couple of examples and ideas on how it can be used.
1. Solve web.config / app.config nightmares
Many times I find that in large applications, I have many web.config / app.config appSettings keys, connection strings, etc and that many of the values have redundant information. For instance server names, IP Addresses or paths may be strewn throughout several appSettings keys and I find myself wishing I could just define the data once, so as to “normalize” my appSettings, and then simply reference one key from the value of another. What I really want is a composition model where I can compose different appSettings (or other strings for that matter) using previously defined values.
Here’s a common scenario:
- I may have a connection string defined with a server name: dbserver01
- I may have environment specific naming conventions like (dbserver01-dev, dbserver01-qa, dbserver01-stg, dbserver01-prod, etc)
- I may have other server names in my appSettings like urls for services, unc paths for fileshares, report server urls, etc.
- While I can certainly duplicate the server names and environment suffix throughout the various appSettings keys, it quickly becomes a chore to make sure these are all correct for a specific environment.
- Web.config transforms help a little bit in that they allow me to define values for different configurations, but it still doesn’t give me a composition model where I can simplify my web.config / app.config settings so that they are easier to manage and maintain. Plus web.config transforms only help at build/deploy time. There is no story for runtime changes.
Expansive aims to solve that problem by allowing for NAnt-like property expansion (scroll down to section 6) whereby I can define an appSetting once such as:
<add key="env" value="dev"/>
And then be able to reuse that value in other settings such as:
<add key="ServerName" value="dbserver01-{env}"/>
And, then finally use that value inside of a connection string such as:
<add name="Default" connectionString="server={ServerName};Initial Catalog=master;uid=uid;pwd=pwd" provider="System.Data.SqlClient"/>
As you can see, I’m defining the “env“ setting once and then reusing that in the “ServerName” setting, which is then used in the connection string.
To get the “expanded” values, you simply call the Expand() extension method on string. For instance:
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString.Expand(); // returns "server=dbserver01-dev;Initial Catalog=master;uid=uid;pwd=pwd"
or you can use the dynamic ConfigurationManager wrapper “Config” as follows:
var connectionString = Config.ConnectionStrings.Default; // returns "server=dbserver01-dev;Initial Catalog=master;uid=uid;pwd=pwd" without needing explicit call to Expand()
By default expansive looks in your web.config or app.config appSettings for the tokens to lookup and expand. However, you can change this or provide your own “source” in the form of a Func<string, string> lambda on the call to Expand() which you’ll see in one of the examples below.
While you obviously have to take care in setting this up the first time, it allows for easily making changes to a series of settings by following a composition model where settings build on one another.
This web.config / app.config example is probably the most common, but this can also be used for string formatting / templating.
2. String Formatting
How many times have you written something like:
var welcomeMessage = string.Format("Hello, {0}", "John");
While it’s a fairly simple example and pretty easy to see from the argument context that the name “John” will get substituted in place of the “{0},” often times these types of strings are in a resource file, config file or database and when looking at them alone and without argument context, it’s not always easy to see what the ‘expectations’ of that string are. For instance if this were localized, it might just read “{0}, {1}” in a resource file. While the key may be something like “welcomeMessage,” it still may not be immediately apparent what that string format requires.
How much more readable and explicit would it be if we could write:
// Simple positional based formatting
// Essentially gets transformed into string.Format("{0} {1}","Hello", "John")
var welcomeMessage = "{greeting}, {firstName}".Expand("Hello", "John");
This is is the simple alternative to string.Format() that Expansive provides in the form of an a simple Expand() extension method on string.
Remember, if I hadn’t provided the arguments (“Hello” and “John”) to the Expand() method, it would have looked for “greeting” and “firstName” keys in my web.config / app.config appSettings. Again, this is just the default, but you can change it globally or on a per call basis. For instance, you could tell Expansive to pull these values out of resource file, a database table, from a webservice, what have you.
Some other ways in which you could accomplish the same thing with Expansive would be:
// Same as above just with variables defined first
// NOTE: This is positional replacement, not actual string interpolation based on variable names
// Again, this gets tranformed into string.Format("{0}, {1}", "Hello", "John")
var greeting = "Hello";
var firstName = "John";
var welcomeMessage = "{greeting}, {firstName}".Expand(greeting, firstName);
or
// Example using a Dictionary<string, string> and containing key/value pairs for expansion
// This could come from a database, file, web service, etc.
var resourceDictionary = new Dictionary<string, string> {
{"greeting","Hello"}
,{"firstName","John"}
};
// call Expand() passing in a custom Func<string, string> lamda for key/value lookup
var welcomeMessage = "{greeting}, {firstName}".Expand(key => resourceDictionary[key]);
Note, you could also do this:
// Example of reusing tokens inside of another string
// NOTE: This is positional replacement, not actual string interpolation based on variable names
// This essentially becomes string.Format("FirstName: {0}, LastName:{1}, FullName: {0} {1}", "John", "Smith")
var firstName = "John";
var lastName = "Smith";
var fullName = "{firstName} {lastName}"
var welcomeMessage = "FirstName: {firstName}, LastName: {lastName}, FullName: {fullName}".Expand(firstName, lastName, fullName);
// NOTE: For fullName to work above, the "{firstName}" "{lastName}" tokens must have been in the string to be expanded.
So, as you can see this is pretty powerful and easy to read in that you can assign friendly names to the tokens vs. just have {0}, {1}, {2}… etc.
3. Model-based Templating
Additionally, Expansive can be used for model-based templating using the Expand(object model) method.
This allows you to do the following:
var model = new { FirstName = "John", LastName = "Smith" };
var testString = "First:{FirstName}, Last:{LastName}".Expand(model);
// returns "First:John, Last:Smith";
Here, Expansive replaces the tokens in the string with the values of the corresponding properties on the passed model object. Nice and clean!
Arguably, this is the most powerful feature and my favorite to use, but I’m curious to get your take.
Download it from GitHub or install it using NuGet and let me know what you think.
Enjoy!


Recent Comments