<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>53 Bytes - by Justin Beckwith</title>
	<atom:link href="http://jbeckwith.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://jbeckwith.com</link>
	<description>A technology blog</description>
	<lastBuildDate>Wed, 30 Jan 2013 05:40:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.2</generator>
		<item>
		<title>Scalable realtime services with Node.js, Socket.IO and Windows Azure</title>
		<link>http://jbeckwith.com/2013/01/30/building-scalable-realtime-services-with-node-js-socket-io-and-windows-azure/</link>
		<comments>http://jbeckwith.com/2013/01/30/building-scalable-realtime-services-with-node-js-socket-io-and-windows-azure/#comments</comments>
		<pubDate>Wed, 30 Jan 2013 05:29:24 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[featured]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[Service Bus]]></category>
		<category><![CDATA[socket.io]]></category>
		<category><![CDATA[WebMatrix]]></category>

		<guid isPermaLink="false">http://jbeckwith.com/?p=539</guid>
		<description><![CDATA[Wazstagram is a fun experiment with node.js on Windows Azure and the Instagram Realtime API.  ]]></description>
			<content:encoded><![CDATA[<p><a href="http://wazstagram.cloudapp.net/"><img alt="WAZSTAGRAM" src="http://jbeckwith.com/wp-content/uploads/2013/01/waz-screenshot.png" title="View the Demo" style="width:100%"/></a>
</p>
</p>
<p><a href="http://wazstagram.cloudapp.net/">Wazstagram</a> is a fun experiment with node.js on <a href="http://www.windowsazure.com/en-us/develop/nodejs/">Windows Azure</a> and the <a href="http://instagram.com/developer/realtime/">Instagram Realtime API</a>.  The project uses various services in Windows Azure to create a scalable window into Instagram traffic across multiple cities.
</p>
<ul>
<li><a href="http://wazstagram.cloudapp.net/">View the demo on Windows Azure</a></li>
<li><a href="https://github.com/JustinBeckwith/wazstagram/">View the code on GitHub</a></li>
</ul>
<p>The code I used to build <a href="https://github.com/JustinBeckwith/wazstagram/" target="_blank">WAZSTAGRAM</a> is under an <a href="https://github.com/JustinBeckwith/wazstagram/blob/master/LICENSE.md" target="_blank">MIT license</a>, so feel free to learn and re-use the code.  </p>
<h1>How does it work</h1>
<p>The application is written in node.js, using cloud services in Windows Azure.  A scalable set of backend nodes receive messages from the Instagram Realtime API.  Those messages are sent to the front end nodes using <a href="http://msdn.microsoft.com/en-us/library/hh690929.aspx">Windows Azure Service Bus</a>.  The front end nodes are running node.js with <a href="http://expressjs.com/">express</a> and <a href="http://socket.io/">socket.io</a>.
</p>
<p>
<a href="http://jbeckwith.com/wp-content/uploads/2013/01/architecture.png" rel="lightbox[539]"><br />
<img alt="WAZSTAGRAM Architecture" title="WAZSTAGRAM Architecture" src="http://jbeckwith.com/wp-content/uploads/2013/01/architecture.png" style="width:100%"/><br />
</a>
</p>
<h2>Websites, and Virtual Machines, and Cloud Services, Oh My!</h2>
<p>One of the first things you need to grok when using Windows Azure is the different options you have for your runtimes.  Windows Azure supports three distinct models, which can be mixed and matched depending on what you&#39;re trying to accomplish:
</p>
<h4>Websites</h4>
<p><a href="http://www.windowsazure.com/en-us/home/scenarios/web-sites/">Websites</a> in Windows Azure match a traditional PaaS model, when compared to something like Heroku or AppHarbor.  They work with node.js, asp.net, and php.  There is a free tier.  You can use git to deploy, and they offer various scaling options.  For an example of a real time node.js site that works well in the Website model, check out my <a href="https://github.com/JustinBeckwith/TwitterMap">TwitterMap</a> example.  I chose not to use Websites for this project because a.) websockets are currently not supported in our Website model, and b.) I want to be able to scale my back end processes independently of the front end processes.  If you don&#39;t have crazy enterprise architecture or scaling needs, Websites work great.
</p>
<h4>Virtual Machines</h4>
<p>The <a href="http://www.windowsazure.com/en-us/home/scenarios/virtual-machines/">Virtual Machine</a> story in Windows Azure is pretty consistent with IaaS offerings in other clouds.  You stand up a VM, you install an OS you like (yes, <a href="http://www.windowsazure.com/en-us/manage/linux/">we support linux</a>), and you take on the management of the host.  This didn&#39;t sound like a lot of fun to me because I can&#39;t be trusted to install patches on my OS, and do other maintainency things.
</p>
<h4>Cloud Services</h4>
<p><a href="http://www.windowsazure.com/en-us/manage/services/cloud-services/">Cloud Services</a> in Windows Azure are kind of a different animal.  They provide a full Virtual Machine that is stateless &#8211; that means you never know when the VM is going to go away, and a new one will appear in it&#39;s place.  It&#39;s interesting because it means you have to architect your app to not depend on stateful system resources pretty much from the start.  It&#39;s great for new apps that you&#39;re writing to be scalable.  The best part is that the OS is patched automagically, so there&#39;s no OS maintenance.  I chose this model because a.) we have some large scale needs, b.) we want separation of conerns with our worker nodes and web nodes, and c.) I can&#39;t be bothered to maintain my own VMs.
</p>
<h1>Getting Started</h1>
<p>After picking your runtime model, the next thing you&#39;ll need is some tools.  Before we move ahead, you&#39;ll need to <a href="http://www.windowsazure.com/en-us/pricing/free-trial/">sign up for an account</a>.  Next, get the command line tools.  Windows Azure is a little different because we support two types of command line tools:
</p>
<ul>
<li><a href="http://www.windowsazure.com/en-us/develop/nodejs/how-to-guides/powershell-cmdlets/">PowerShell Cmdlets</a>: these are great if you&#39;re on Windows and dig the PowerShell thing.
</li>
<li><a href="http://www.windowsazure.com/en-us/manage/linux/other-resources/command-line-tools/">X-Platform CLI</a>:  this tool is interesting because it&#39;s written in node, and is available as a node module.  You can actually just <code>npm install -g azure-cli</code> and start using this right away.  It looks awesome, though I wish they had kept the flames that were in the first version.
</li>
</ul>
<p>
<a href="http://jbeckwith.com/wp-content/uploads/2013/01/cli.png" rel="lightbox[539]"><br />
<img alt="X-Plat CLI" title="X-Plat CLI" src="http://jbeckwith.com/wp-content/uploads/2013/01/cli.png" style="width:100%" /><br />
</a>
</p>
<p>For this project, I chose to use the PowerShell cmdlets.  I went down this path because the Cloud Services stuff is not currently supported by the X-Platform CLI (I&#39;m hoping this changes).  If you&#39;re on MacOS and want to use Cloud Services, you should check out <a href="https://github.com/tjanczuk/git-azure">git-azure</a>.   To bootstrap the project, I pretty much followed the <a href="http://www.windowsazure.com/en-us/develop/nodejs/tutorials/app-using-socketio/">&#39;Build a Node.js Chat Application with Socket.IO on a Windows Azure Cloud Service&#39; tutorial</a>.  This will get all of your scaffolding set up.
</p>
<h2>My node.js editor &#8211; WebMatrix 2</h2>
<p>After using the PowerShell cmdlets to scaffold my site, I used <a href="http://www.microsoft.com/web/webmatrix/">Microsoft WebMatrix</a> to do the majority of the work.  I am very biased towards WebMatrix, as I helped <a href="http://jbeckwith.com/2012/06/07/node-js-meet-webmatrix-2/">build the node.js experience</a> in it last year.  In a nutshell, it&#39;s rad because it has a lot of good editors, and just works.  Oh, and it has IntelliSense for everything:
</p>
<p>
<a href="http://jbeckwith.com/wp-content/uploads/2013/01/webmatrix.png" rel="lightbox[539]"><br />
<img alt="I &lt;3 WebMatrix" title="WebMatrix FTW" src="http://jbeckwith.com/wp-content/uploads/2013/01/webmatrix.png" style="width:100%"/><br />
</a>
</p>
<h3>Install the Windows Azure NPM module</h3>
<p>The <a href="https://npmjs.org/package/azure">azure npm module</a> provides the basis for all of the Windows Azure stuff we&#39;re going to do with node.js.  It includes all of the support for using blobs, tables, service bus, and service management.  It&#39;s even <a href="https://github.com/WindowsAzure/azure-sdk-for-node/">open source</a>.  To get it, you just need to cd into the directory you&#39;re using and run this command:
</p>
<p><code>npm install azure</code>
</p>
<p>After you have the azure module, you&#39;re ready to rock.
</p>
</li>
</ol>
<h1>The Backend</h1>
<p>The <a href="https://github.com/JustinBeckwith/wazstagram/tree/master/backend">backend</a> part of this project is a worker role that accepts HTTP Post messages from the Instagram API.  The idea is that their API batches messages, and sends them to an endpoint you define.  Here&#39;s <a href="http://instagram.com/developer/realtime/">some details</a> on how their API works.  I chose to use <a href="http://expressjs.com/">express</a> to build out the backend routes, because it&#39;s convenient.  There are a few pieces to the backend that are interesting:
</p>
<ol>
<li>
<h4>Use <a href="https://github.com/flatiron/nconf">nconf</a> to store secrets.  Look at the .gitignore.</h4>
<p>If you&#39;re going to build a site like this, you are going to need to store a few secrets.  The backend includes things like the Instagram API key, my Windows Azure Storage account key, and my Service Bus keys.  I create a keys.json file to store this, though you could add it to the environment.  I include an example of this file with the project.  **DO NOT CHECK THIS FILE INTO GITHUB!**  Seriously, <a href="https://github.com/blog/1390-secrets-in-the-code" target="_blank">don&#39;t do that</a>.  Also, pay **close attention** to my <a href="https://github.com/JustinBeckwith/wazstagram/blob/master/.gitignore" target="_blank">.gitignore file</a>.  You don&#39;t want to check in any *.cspkg or *.csx files, as they contain archived versions of your site that are generated while running the emulator and deploying.  Those archives contain your keys.json file.  That having been said &#8211; nconf does makes it really easy to read stuff from your config:</p>
<pre class="brush: jscript; title: ;">
// read in keys and secrets
nconf.argv().env().file('keys.json');
var sbNamespace = nconf.get('AZURE_SERVICEBUS_NAMESPACE');
var sbKey = nconf.get('AZURE_SERVICEBUS_ACCESS_KEY');
var stName = nconf.get('AZURE_STORAGE_NAME');
var stKey = nconf.get('AZURE_STORAGE_KEY');
</pre>
</li>
<li>
<h4>Use <a href="https://github.com/flatiron/winston">winston</a> and <a href="https://github.com/pofallon/winston-skywriter">winston-skywriter</a> for logging.</h4>
<p>The cloud presents some challenges at times.  Like *how do I get console output* when something goes wrong.  Every node.js project I start these days, I just use winston from the get go.  It&#39;s awesome because it lets you pick where your console output and logging gets stored.  I like to just pipe the output to console at dev time, and write to <a href="http://www.windowsazure.com/en-us/develop/nodejs/how-to-guides/table-services/" target="_blank">Table Storage</a> in production.  Here&#39;s how you set it up:</p>
<pre class="brush: jscript; title: ;">
// set up a single instance of a winston logger, writing to azure table storage
var logger = new (winston.Logger)({
    transports: [
        new (winston.transports.Console)(),
        new (winston.transports.Skywriter)({
            account: stName,
            key: stKey,
            partition: require('os').hostname() + ':' + process.pid
        })
    ]
});

logger.info('Started wazstagram backend');
</pre>
</li>
<li>
<h4>Use <a href="http://msdn.microsoft.com/en-us/library/ee732537.aspx">Service Bus</a> &#8211; it&#39;s pub/sub (+) a basket of kittens.</h4>
<p>
<a href="http://msdn.microsoft.com/en-us/library/ee732537.aspx" target="_blank">Service Bus</a> is Windows Azure&#8217;s swiss army knife of messaging.  I usually use it in the places where I would otherwise use the PubSub features of Redis.  It does all kinds of neat things like <a href="http://www.windowsazure.com/en-us/develop/net/how-to-guides/service-bus-topics/" target="_blank">PubSub</a>, <a href="http://msdn.microsoft.com/en-us/library/windowsazure/hh767287.aspx" target="_blank">Durable Queues</a>, and more recently <a href="https://channel9.msdn.com/Blogs/Subscribe/Service-Bus-Notification-Hubs-Code-Walkthrough-Windows-8-Edition" target="_blank">Notification Hubs</a>.   I use the topic subscription model to create a single channel for messages.  Each worker node publishes messages to a single topic.  Each web node creates a subscription to that topic, and polls for messages.  There&#8217;s great <a href="http://www.windowsazure.com/en-us/develop/nodejs/how-to-guides/service-bus-topics/" target="_blank">support for Service Bus</a> in the <a href="https://github.com/WindowsAzure/azure-sdk-for-node" target="_blank">Windows Azure Node.js SDK</a>.
</p>
<p>
To get the basic implementation set up, just follow the <a href="http://www.windowsazure.com/en-us/develop/nodejs/how-to-guides/service-bus-topics/" target="_blank">Service Bus Node.js guide</a>. The interesting part of my use of Service Bus is the subscription clean up.  Each new front end node that connects to the topic creates it&#39;s own subscription.  As we scale out and add a new front end node, it creates another subscription.  This is a durable object in Service bus that hangs around after the connection from one end goes away (this is a feature).  To make sure sure you don&#39;t leave random subscriptions lying around, you need to do a little cleanup:
</p>
<pre class="brush: jscript; title: ;">
function cleanUpSubscriptions() {
    logger.info('cleaning up subscriptions...');
    serviceBusService.listSubscriptions(topicName, function (error, subs, response) {
        if (!error) {
            logger.info('found ' + subs.length + ' subscriptions');
            for (var i = 0; i &lt; subs.length; i++) {
                // if there are more than 100 messages on the subscription, assume the edge node is down
                if (subs[i].MessageCount &gt; 100) {
                    logger.info('deleting subscription ' + subs[i].SubscriptionName);
                    serviceBusService.deleteSubscription(topicName, subs[i].SubscriptionName, function (error, response) {
                        if (error) {
                            logger.error('error deleting subscription', error);
                        }
                    });
                }
            }
        } else {
            logger.error('error getting topic subscriptions', error);
        }
        setTimeout(cleanUpSubscriptions, 60000);
    });
}
</pre>
</li>
<li>
<h4>The <a href="https://github.com/JustinBeckwith/wazstagram/blob/master/backend/routes/home.js">NewImage endpoint</a></h4>
<p>All of the stuff above is great, but it doesn&#8217;t cover what happens when the Instagram API actually hits our endpoint.  The route that accepts this request gets metadata for each image, and pushes it through the Service Bus topic:</p>
<pre class="brush: jscript; title: ;">
serviceBusService.sendTopicMessage('wazages', message, function (error) {
	if (error) {
        logger.error('error sending message to topic!', error);
    } else {
        logger.info('message sent!');
    }
})
</pre>
</li>
</ol>
<h1>The Frontend</h1>
<p>The <a href="https://github.com/JustinBeckwith/wazstagram/tree/master/frontend">frontend</a> part of this project is (despite my &#39;web node&#39; reference) a worker role that accepts accepts the incoming traffic from end users on the site.  I chose to use worker roles because I wanted to take advantage of Web Sockets.  At the moment, Cloud Services Web Roles do not provide that functionality.  I could stand up a VM with Windows Server 8 and IIS 8, but see my aformentioned anxiety about managing my own VMs.  The worker roles use <a href="http://socket.io/">socket.io</a> and <a href="http://expressjs.com">express</a> to provide the web site experience.  The front end uses the same NPM modules as the backend:  <a href="https://github.com/visionmedia/express/">express</a>, <a href="https://github.com/flatiron/winston">winston</a>, <a href="https://github.com/pofallon/winston-skywriter">winston-skywriter</a>, <a href="https://github.com/flatiron/nconf">nconf</a>, and <a href="https://github.com/WindowsAzure/azure-sdk-for-node">azure</a>.  In addition to that, it uses <a href="http://socket.io/">socket.io</a> and <a href="https://github.com/visionmedia/ejs">ejs</a> to handle the client stuff.  There are a few pieces to the frontend that are interesting:
</p>
<ol>
<li>
<h4>Setting up socket.io</h4>
<p>Socket.io provides the web socket (or xhr) interface that we&#39;re going to use to stream images to the client.  When a user initially visits the page, they are going to send a `setCity` call, that lets us know the city to which they want to subscribe (by default all <a href="https://github.com/JustinBeckwith/wazstagram/blob/master/backend/cities.json" target="_blank">cities in the system</a> are returned).  From there, the user will be sent an initial blast of images that are cached on the server.  Otherwise, you wouldn&#39;t see images right away:</p>
<pre class="brush: jscript; title: ;">
// set up socket.io to establish a new connection with each client
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
    socket.on('setCity', function (data) {
        logger.info('new connection: ' + data.city);
        if (picCache[data.city]) {
            for (var i = 0; i &lt; picCache[data.city].length; i++) {
                socket.emit('newPic', picCache[data.city][i]);
            }
        }
        socket.join(data.city);
    });
});
</pre>
</li>
<li>
<h4>Creating a Service Bus Subscription</h4>
<p>To receive messages from the worker nodes, we need to create a single subscription for each front end node process.  This is going to create subscription, and start listening for messages:</p>
<pre class="brush: jscript; title: ;">
// create the initial subscription to get events from service bus
serviceBusService.createSubscription(topicName, subscriptionId,
    function (error) {
        if (error) {
            logger.error('error creating subscription', error);
            throw error;
        } else {
            getFromTheBus();
        }
});
</pre>
</li>
<li>
<h4>Moving data between Service Bus and Socket.IO</h4>
<p>As data comes in through the service bus subscription, you need to pipe it up to the appropriate connected clients.  Pay special attention to `io.sockets.in(body.city)` &#8211; when the user joined the page, they selected a city.  This call grabs all users subscribed to that city.  The other **important thing to notice** here is the way `getFromTheBus` calls itself in a loop.  There&#39;s currently no way to say &quot;just raise an event when there&#39;s data&quot; with the Service Bus Node.js implementation, so you need to use this model.  </p>
<pre class="brush: jscript; title: ;">
function getFromTheBus() {
    try {
        serviceBusService.receiveSubscriptionMessage(topicName, subscriptionId, { timeoutIntervalInS: 5 }, function (error, message) {
            if (error) {
                if (error == &quot;No messages to receive&quot;) {
                    logger.info('no messages...');
                } else {
                    logger.error('error receiving subscription message', error)
                }
            } else {
                var body = JSON.parse(message.body);
                logger.info('new pic published from: ' + body.city);
                cachePic(body.pic, body.city);
                io.sockets. in (body.city).emit('newPic', body.pic);
                io.sockets. in (universe).emit('newPic', body.pic);
            }
            getFromTheBus();
        });
    } catch (e) {
        // if something goes wrong, wait a little and reconnect
        logger.error('error getting data from service bus' + e);
        setTimeout(getFromTheBus, 1000);
    }
}
</pre>
</li>
</ol>
<h1>Learning</h1>
<p>The whole point of writing this code for me was to explore building performant apps that used a rate limited API for data.  Hopefully this model can effectively be used to accept data from any API responsibly, and scale it out to a number of connected clients to a single service.  If you have any ideas on how to make this app better, please let me know, or submit a PR!
</p>
<h1>Questions?</h1>
<p>If you have any questions, feel free to submit an issue here, or find me <a href="https://twitter.com/JustinBeckwith" target="_blank">@JustinBeckwith</a></p>
]]></content:encoded>
			<wfw:commentRss>http://jbeckwith.com/2013/01/30/building-scalable-realtime-services-with-node-js-socket-io-and-windows-azure/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>5 steps to a better Windows command line</title>
		<link>http://jbeckwith.com/2012/11/28/5-steps-to-a-better-windows-command-line/</link>
		<comments>http://jbeckwith.com/2012/11/28/5-steps-to-a-better-windows-command-line/#comments</comments>
		<pubDate>Wed, 28 Nov 2012 06:26:11 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Console]]></category>
		<category><![CDATA[featured]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[Posh-Git]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://jbeckwith.com/?p=481</guid>
		<description><![CDATA[I spend a lot of time at the command line. As someone who likes to code on OSX and Windows, I&#8217;ve always been annoyed by the Windows command line experience. Do I use cmd, or PowerShell? Where are my tabs? What about package management? What about little frivolous things like being able to resize the [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://jbeckwith.com/wp-content/uploads/2012/11/header.png" rel="lightbox[481]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/11/header.png" style="width:100%" ><br />
</a></p>
<p>I spend a lot of time at the command line.  As someone who likes to code on OSX and Windows, I&#8217;ve always been annoyed by the Windows command line experience.  Do I use cmd, or PowerShell?  Where are my tabs?  What about package management?  What about little frivolous things like <em>being able to resize the window</em>.  I&#8217;ve finally got my Windows command line experience running smoothly, and wanted to share my setup.  Here are my 5 steps to a Windows command line that doesn&#8217;t suck.</p>
<h1>1. Use Console2 or ConEmu</h1>
<p>The first place to start is the actual console application.  Scott Hanselman wrote an <a href="http://www.hanselman.com/blog/Console2ABetterWindowsCommandPrompt.aspx" target="_blank">excellent blog post</a> on setting up <a href="http://sourceforge.net/projects/console/" target="_blank">Console2</a>, and I&#8217;ve been using it ever since.  It adds tabs, a resizable window, transparency, and the ability to run multiple shells.  I choose to run PowerShell (you should too, keep listening).  There are <a href="http://www.hanselman.com/blog/ConEmuTheWindowsTerminalConsolePromptWeveBeenWaitingFor.aspx" target="_blank">other options</a> out there, but I&#8217;ve really grown to love Console2.<br />
<a href="http://jbeckwith.com/wp-content/uploads/2012/11/console2.png" rel="lightbox[481]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/11/console2.png" alt="Console2" style="width:100%"><br />
</a></p>
<h1>2. Use PowerShell</h1>
<p>I won&#8217;t spend a ton of time evangelizing PowerShell.  There are a few good reasons to dump cmd.exe and move over:</p>
<ul>
<li><b>Most of the things you do in cmd will just work.</b>  There are obviously some exceptions, but for the better part all of the things I want to do in cmd are easily done in PowerShell. </li>
<li><b><a href="http://blogs.msdn.com/b/powershell/archive/2008/01/31/tab-completion.aspx" target="_blank">Tab Completion</a> and <a href="http://technet.microsoft.com/en-us/library/ee176848.aspx" target="_blank">Get-Help</a> is awesome.</b>  PowerShell does a great job of making things discoverable as you learn.
<li><b>It&#8217;s a sane scripting tool.</b>  If you&#8217;ve ever tried to do anything significant in a batch script, I&#8217;m sorry.  You can even create your <a href="http://community.bartdesmet.net/blogs/bart/archive/2008/02/03/easy-windows-powershell-cmdlet-development-and-debugging.aspx" target="_blank">own modules and cmdlets</a> using managed code, if that&#8217;s your thing.</li>
<li><b>Microsoft is releasing a lot of stuff built on PowerShell.</b>  Most of the new stuff we release is going to have great PowerShell support, including <a href="http://msdn.microsoft.com/en-us/library/windowsazure/jj156055.aspx" target="_blank">Windows Azure</a>.  </li>
<li><b>It&#8217;s a growing community.</b>  Sites like <a href="http://powershell.org/" target="_blank">PowerShell.org</a> and <a href="http://psget.net/" target="_blank">PsGet</a> provide a great place to ask questions and look at work others have done.
</ul>
<p>Now that I&#8217;ve sold you, there are a few things you&#8217;ll find through here that make using PowerShell a bit easier.  To use this stuff, you&#8217;re going to want to set an execution policy in PowerShell that lets you run custom scripts.  By default, the execution of PS scripts is disabled, but it&#8217;s kind of necessary to do anything interesting.  I lead a wild and dangerous life, so I use an unrestricted policy.  To set your policy, first run Console2 (or PowerShell) as an administrator:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/11/console2-as-administrator.png" rel="lightbox[481]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/11/console2-as-administrator.png"><br />
</a></p>
<style type="text/css">
.syntaxhighlighter table td.code .line {
    white-space: pre-wrap !important;
    word-wrap: break-word !important;
}
</style>
<p>Next, use the Set-ExecutionPolicy command.  Note, this means any un-signed script can be run on your system, if you run it, and many people choose to use RemoteSigned.  Here is the <a href="" target="_blank">official doc on Set-ExecutionPolicy</a>.  </p>
<pre class="brush: powershell; title: ;">
Set-ExecutionPolicy Unrestricted
</pre>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/11/set-executionpolicy.png" rel="lightbox[481]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/11/set-executionpolicy.png" width="100%"><br />
</a></p>
<p>Now you&#8217;re ready to start doing something interesting.</p>
<h1>3. Use the Chocolatey package manager</h1>
<p>Spending a lot of time in Ubuntu and OSX, I got really used to `sudo apt-get install
<package>` and `<a href="http://mxcl.github.com/homebrew/" target="_blank">brew</a> install
<package>`.  The closest I&#8217;ve found to that experience on Windows is the <a href="http://chocolatey.org/" target="_blank">Chocolatey package manager</a>.  Chocolatey has all of the packages you would expect to find on a developer&#8217;s machine:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/11/choc-list.png" rel="lightbox[481]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/11/choc-list.png" style="width:100%" alt="list packages"><br />
</a></p>
<p>To install Chocolatey, just run cmd.exe and run the following command (minus the c:\> part):</p>
<pre class="brush: powershell; title: ;">
C:\&gt; @powershell -NoProfile -ExecutionPolicy unrestricted -Command &quot;iex ((new-object net.webclient).DownloadString('http://bit.ly/psChocInstall'))&quot; &amp;&amp; SET PATH=%PATH%;%systemdrive%\chocolatey\bin
</pre>
<p>And you&#8217;re ready to rock.  If you want to install something like 7zip, you can use the cinst command:</p>
<pre class="brush: powershell; title: ;">
cinst 7zip
</pre>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/11/7zip-install.png" rel="lightbox[481]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/11/7zip-install.png" style="width:100%" alt="install 7zip"><br />
</a></p>
<h1>4. Use an alias for SublimeText</h1>
<p>This seems kind of trivial, but one of the things I&#8217;ve really missed on Windows is the default shortcut to launch <a href="http://www.sublimetext.com/" target="_blank">SublimeText</a>, <a href="http://www.sublimetext.com/docs/2/osx_command_line.html" target="_blank">subl</a>.  I use my PowerShell profile to create an alias to SublimeText.exe, which allows me to `subl file.txt` or `subl .` just like I would from OSX.  <a href="http://www.howtogeek.com/50236/customizing-your-powershell-profile/" target="_blank">This article</a> gives a basic overview on how to customize your PowerShell Profile; it&#8217;s really easy to follow, so I won&#8217;t go into re-creating the steps.  </p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/11/create-profile.png" rel="lightbox[481]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/11/create-profile.png" style="width: 100%"><br />
</a></p>
<p>After you&#8217;ve got your PowerShell profile created, edit the script, and add this line:</p>
<pre class="brush: powershell; title: ;">
Set-Alias subl 'C:\Program Files\Sublime Text 2\sublime_text.exe'
</pre>
<p>Save your profile, and spin up a new PowerShell tab in Console2 to reload the session.  Go to a directory that contains some code, and try to open it:</p>
<pre class="brush: powershell; title: ;">
subl .
</pre>
<p>This will load the current directory as a project in SublimeText from the command line.  Small thing, but a nice thing.</p>
<h1>5. Use PsGet and Posh-Git</h1>
<p>One of the nice things about using PowerShell over cmd is the community that&#8217;s starting to emerge.  There are a ton of really useful tools and cmdlets that others have already written, and the easiest way to get at most of these is to use <a href="http://psget.net/" target="_blank">PsGet</a>.  PsGet provides a super easy way to install PowerShell modules that extend the basic functionality of the shell, and provide other useful libraries.  To install PsGet, run the following command from a PowerShell console:</p>
<pre class="brush: powershell; title: ;">
(new-object Net.WebClient).DownloadString(&quot;http://psget.net/GetPsGet.ps1&quot;) | iex
</pre>
<p>If you get an error complaining about executing scripts, you need to go back to #2.   Immediately, we can start using the `Install-Module` command to start adding functionality to our console.  </p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/11/psget.png" rel="lightbox[481]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/11/psget.png" style="width:100%" alt="Install PsGet"><br />
</a></p>
<p>The first module that led me to PsGet is a package that adds status and tab completion to git.  Phil Haack did a <a href="http://haacked.com/archive/2011/12/13/better-git-with-powershell.aspx" target="_blank">great write up</a> on setting up <a href="https://github.com/dahlbyk/posh-git/" target="_blank">posh-git</a>, and I&#8217;ve since discovered a few other <a href="http://pscx.codeplex.com" target="_blank">cool things</a> in the PsGet gallery.  Installing Posh-Git is pretty straight forward:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/11/install-posh-git.png" rel="lightbox[481]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/11/install-posh-git.png" style="width:100%" alt="Install Posh-Git"><br />
</a></p>
<p>The first nice thing here is that I now have command completion.  As I type `git sta` and hit <tab>, it will be completed to `git status`.  Some tools like <a href="https://github.com/MSOpenTech/posh-npm" target="_blank">posh-npm</a> will even search the npm registry for packages using tab completion.   The other cool thing you get with this module is the status of your repository right in the prompt:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/11/posh-git-status.png" rel="lightbox[481]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/11/posh-git-status.png" style="width:100%" alt="posh git"><br />
</a></p>
<h1>Wrapping up</h1>
<p>These are just the ways I know how to make the command line experience better.  If any one else has some tips, I&#8217;d love to hear them!</p>
]]></content:encoded>
			<wfw:commentRss>http://jbeckwith.com/2012/11/28/5-steps-to-a-better-windows-command-line/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>WebMatrix and Node Package Manager</title>
		<link>http://jbeckwith.com/2012/09/07/webmatrix-and-node-package-manager/</link>
		<comments>http://jbeckwith.com/2012/09/07/webmatrix-and-node-package-manager/#comments</comments>
		<pubDate>Fri, 07 Sep 2012 21:13:39 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WebMatrix]]></category>
		<category><![CDATA[node]]></category>

		<guid isPermaLink="false">http://jbeckwith.com/?p=467</guid>
		<description><![CDATA[The new Node Package Manager (NPM) extension for WebMatrix gives a visual experience for managing packages in nodejs applications.]]></description>
			<content:encoded><![CDATA[<p><img src="http://jbeckwith.com/wp-content/uploads/2012/09/node_128.png" alt="NPM and WebMatrix"  /></p>
<p>A few months ago, we introduced the new <a href="http://jbeckwith.com/2012/06/07/node-js-meet-webmatrix-2/" target="_blank">node.js features we&#8217;ve added to WebMatrix 2</a>.  One of the missing pieces from that experience was a way to manage <a href="https://npmjs.org/" target="_blank">NPM</a> (Node Package Manager) from within the IDE.  </p>
<p>This week we shipped the final release of WebMatrix 2, and one of the fun things that comes with it is a new extension for managing NPM.  For a more complete overview of the WebMatrix 2, check out <a href="http://vishaljoshi.blogspot.com/2012/06/announcing-webmatrix-2-rc.html" target="_blank">Vishal Joshi&#8217;s blog post</a>.</p>
<p>If you want to skip all of this and just download the bits, here you go:</p>
<p><a href="http://go.microsoft.com/?linkid=9809776" target="_blank"><img style="display: inline" title="image" alt="image" src="http://lh5.ggpht.com/-lm1GuUL20p8/T9HReoCZk7I/AAAAAAAABU4/uO7oVvNCGPQ/image%25255B4%25255D.png?imgmax=800" width="170" height="45"></a></p>
<h1>Installing the Extension</h1>
<p>The NPM extension can be installed using the extension gallery inside of WebMatrix.  To get started, go ahead and create a new node site with express using the built in template:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/09/template.png" rel="lightbox[467]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/09/template.png" alt="Create a new express site" class="alignnone"  style="width:100%"   /><br />
</a></p>
<p>After you create the site, click on the &#8216;Extensions&#8217; button in the ribbon:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/09/extension-gallery-icon.png" rel="lightbox[467]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/09/extension-gallery-icon.png" alt="WebMatrix Extension Gallery" class="alignnone" style="width:100%"   /><br />
</a></p>
<p>Search for &#8216;NPM&#8217;, and click through the wizard to finish installing the extension:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/09/npm-extension.png" rel="lightbox[467]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/09/npm-extension.png" alt="Install the NPM Gallery Extension" class="alignnone"  style="width:100%"   /><br />
</a></p>
<p>Now when you navigate to the files workspace, you should see the new NPM icon in the ribbon.</p>
<h1>Managing Packages</h1>
<p>While you&#8217;re working with node.js sites, the icon should always show up.  To get started, click on the new icon in the ribbon:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/09/npm-icon.png" rel="lightbox[467]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/09/npm-icon.png" alt="NPM Icon in the ribbon" class="alignnone" style="width:100%"   /><br />
</a></p>
<p>This will load a window very similar to the other galleries in WebMatrix.  From here you can search for packages, install, uninstall, update, any of the basic tasks you&#8217;re likely to do day to day with npm.  </p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/09/npm-dialog.png" rel="lightbox[467]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/09/npm-dialog.png" alt="NPM Gallery" class="alignnone"  style="width:100%"   /><br />
</a></p>
<p>When you open up a new site, we also check your package.json to see if you&#8217;re missing any dependencies:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/09/missing-packages.png" rel="lightbox[467]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/09/missing-packages.png" alt="Missing NPM packages" class="alignnone"  /><br />
</a></p>
<p>We&#8217;re just getting started with the node tools inside of WebMatrix, so if you have anything else you would like to see added please hit us up over at <a href="https://webmatrix.uservoice.com" target="_blank">UserVoice</a>. </p>
<h1>More Information</h1>
<p>If you would like some more information to help you get started, check out some of these links:</p>
<ul>
<li><a href="http://bit.ly/LG7gs8" target="_blank">WebMatrix on Microsoft.com</a></li>
<li><a href="https://twitter.com/#!/webmatrix" target="_blank">WebMatrix on Twitter</a></li>
<li><a href="https://github.com/MicrosoftWebMatrix" target="_blank">WebMatrix on GitHub</a></li>
<li><a href="http://webmatrix.uservoice.com" target="_blank">WebMatrix on UserVoice</a></li>
<li><a href="http://www.microsoft.com/Web/webmatrix/optimize.aspx" target="_blank">WebMatrix and Open Source Applications</a></li>
<li><a href="http://vishaljoshi.blogspot.com/2012/06/announcing-webmatrix-2-rc.html" target="_blank">Vishal Joshi&#8217;s blog post</a></li>
</ul>
<h2>Happy Coding!</h2>
]]></content:encoded>
			<wfw:commentRss>http://jbeckwith.com/2012/09/07/webmatrix-and-node-package-manager/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>WordPress and WebMatrix</title>
		<link>http://jbeckwith.com/2012/06/09/wordpress-and-webmatrix/</link>
		<comments>http://jbeckwith.com/2012/06/09/wordpress-and-webmatrix/#comments</comments>
		<pubDate>Sat, 09 Jun 2012 04:59:25 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WebMatrix]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[featured]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://jbeckwith.com/?p=433</guid>
		<description><![CDATA[WebMatrix 2 provides a great experience for WordPress developers who need PHP Code Completion, MySQL database editors, and advanced publishing tools.]]></description>
			<content:encoded><![CDATA[<p><img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_title_header.png" alt="WordPress and WebMatrix"  /></p>
<p>After releasing WebMatrix 2 RC this week, I&#8217;m excited to head out to NYC for WordCamp 2012.  While I get ready to present tomorrow,  I figured I would share some of the amazing work the WebMatrix team has done to create a great experience for WordPress developers.  For a more complete overview of the WebMatrix 2 RC, check out <a href="http://vishaljoshi.blogspot.com/2012/06/announcing-webmatrix-2-rc.html" target="_blank">Vishal Joshi&#8217;s blog post</a>.</p>
<p>If you want to skip all of this and just download the bits, here you go:</p>
<p><a href="http://bit.ly/L77V6w" target="_blank"><img style="display: inline" title="image" alt="image" src="http://lh5.ggpht.com/-lm1GuUL20p8/T9HReoCZk7I/AAAAAAAABU4/uO7oVvNCGPQ/image%25255B4%25255D.png?imgmax=800" width="170" height="45"></a></p>
<h1>Welcome to WebMatrix</h1>
<p>WebMatrix gives you a couple of ways to get started with your application.  Anything we do is going to be focused on building web applications, with as few steps as possible.  WebMatrix supports opening remote sites, opening local sites, creating new sites with PHP, or creating an application by starting with the Application Gallery.</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_start_screen.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_start_screen.png" alt="Welcome to WebMatrix" class="alignnone" style="width:100%"    /><br />
</a></p>
<h1>The Application Gallery</h1>
<p>We work with the community to maintain a list of open source applications that just work with WebMatrix on the Windows platform.  This includes installing the application locally, and deploying to Windows Server or Windows Azure:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_app_gallery.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_app_gallery.png" alt="WebMatrix application gallery" class="alignnone" style="width:100%"   /><br />
</a></p>
<h1>Install PHP and MySQL Automatically</h1>
<p>When you pick the application you want to install, WebMatrix knows what dependencies need to be installed on your machine.  This means you don&#8217;t need to set up a web server, install and configure MySQL, mess around with the MySQL command line &#8211; none of that.  It all just happens auto-magically.</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_dependencies.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_dependencies.png" alt="Install and setup automatically" class="alignnone" style="width:100%"    /><br />
</a></p>
<h1>The Dashboard</h1>
<p>After installing WordPress and all of it&#8217;s dependencies, WebMatrix provides you with a dashboard that&#8217;s been customized for WordPress.  We open up an extensibility model that makes it easier for open source communities to plug into WebMatrix, and we&#8217;ve been working with several groups to make sure we provide this kind of experience:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_dashboard.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_dashboard_clipped.png" alt="WordPress Dashboard" class="alignnone" style="width:100%"   /><br />
</a></p>
<h1>Protected Files</h1>
<p>When you move into the files work space, you&#8217;ll notice a lock file next to many of the files in the root.  We worked with the WordPress community to define a list of files that are protected in WordPress.  These are files that power the core of WordPress, and probably shouldn&#8217;t be changed:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_locked_files.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_locked_files.png" alt="Locked system files" class="alignnone"   /><br />
</a></p>
<p>We won&#8217;t stop you from editing the file, but hopefully this prevents people from making mistakes:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_lock_warning.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_lock_warning.png" alt="WebMatrix saves you from yourself" class="alignnone"   /><br />
</a></p>
<h1>HTML5 &#038; CSS3 Tools</h1>
<p>The HTML editor in WebMatrix has code completion, validation, and formatting for HTML5.  The editor is really, really good.  The CSS editor includes code completion, validation, and formatting for CSS3, including the latest and greatest CSS3 modules.  We also include support for CSS preprocessors like LESS and Sass.  </p>
<p>I think my favorite part about the CSS editor is the way it makes dealing with color easier.  If you start off a color property, WebMatrix will look at the current CSS file, and provide a palette built from the other colors used throughout your site.  This prevents you from having 17 shades of the mostly same color blue:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_color_pallette.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_color_pallette.png" alt="The CSS Color Palette" class="alignnone"   /><br />
</a></p>
<p>If you want to add a new color, we also have a full color picker.  This thing is awesome &#8211; my favorite part is the eye dropper that lets you choose colors in other applications.</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_color_picker.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_color_picker.png" alt="The CSS Color Picker" class="alignnone" style="width:100%"   /><br />
</a></p>
<h1>PHP Code Completion</h1>
<p>When you&#8217;re ready to start diving into PHP, we include a fancy new PHP editor.  It provides code completion with documentation from php.net, and a lot of other little niceties that make writing PHP easier:<br />
<a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_php_intellisense.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_php_intellisense.png" alt="PHP Code Completion" class="alignnone" style="width:100%"   /><br />
</a></p>
<h1>WordPress Code Completion</h1>
<p>So you&#8217;ve written some PHP, but now you want to start using the built-in functions available in WordPress.  We worked with the WordPress community to come up with a list of supported functions, along with documentation on how they work.  Any open source application in the gallery can provide this kind of experience:<br />
<a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_intellisense.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_intellisense.png" alt="WordPress specific Code Completion" class="alignnone" style="width:100%"   /><br />
</a></p>
<h1>MySQL Database Editor</h1>
<p>If you need to make changes directly to the database, WebMatrix has a full featured MySQL editor built right into the product.  You can create tables, manage keys, or add data right through the UI.  No command line needed.<br />
<a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_mysql.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_mysql.png" alt="MySQL Database Manager" class="alignnone" style="width:100%"   /><br />
</a></p>
<h1>Remote Editing</h1>
<p>If you need to make edits to a live running site, we can do that to.  Just enter your connection information (FTP or Web Deploy), and you can start editing your files without dealing with a FTP client:<br />
<a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_start_remote.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_start_remote.png" alt="Open a remote site" class="alignnone"   /><br />
</a></p>
<p>After you make your changes, just save the file to automatically upload it to your server:<br />
<a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_remote_code.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_remote_code.png" alt="Edit files remotely" class="alignnone"   /><br />
</a></p>
<h1>Easy Publishing</h1>
<p>When you&#8217;re ready to publish your application, you have the choice of using FTP or Web Deploy.  If you use Web Deploy, we can even publish your database automatically along with the files in your WordPress site.  When you make subsequent publish calls, only the changed files are published:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/wp_publish.png" rel="lightbox[433]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/wp_publish.png" alt="Easy Publishing" class="alignnone" style="width:100%"    /><br />
</a></p>
<h1>More Information</h1>
<p>If you would like some more information to help you get started, check out some of these links:</p>
<ul>
<li><a href="http://bit.ly/LG7gs8" target="_blank">WebMatrix on Microsoft.com</a></li>
<li><a href="https://twitter.com/#!/webmatrix" target="_blank">WebMatrix on Twitter</a></li>
<li><a href="https://github.com/MicrosoftWebMatrix" target="_blank">WebMatrix on GitHub</a></li>
<li><a href="http://webmatrix.uservoice.com" target="_blank">WebMatrix on UserVoice</a></li>
<li><a href="http://www.microsoft.com/Web/webmatrix/optimize.aspx" target="_blank">WebMatrix and Open Source Applications</a></li>
<li><a href="http://vishaljoshi.blogspot.com/2012/06/announcing-webmatrix-2-rc.html" target="_blank">Vishal Joshi&#8217;s blog post</a></li>
</ul>
<h2>Happy Coding!</h2>
]]></content:encoded>
			<wfw:commentRss>http://jbeckwith.com/2012/06/09/wordpress-and-webmatrix/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Node.js meet WebMatrix 2</title>
		<link>http://jbeckwith.com/2012/06/07/node-js-meet-webmatrix-2/</link>
		<comments>http://jbeckwith.com/2012/06/07/node-js-meet-webmatrix-2/#comments</comments>
		<pubDate>Thu, 07 Jun 2012 03:38:56 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[WebMatrix]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[CoffeeScript]]></category>
		<category><![CDATA[featured]]></category>
		<category><![CDATA[less]]></category>
		<category><![CDATA[sass]]></category>

		<guid isPermaLink="false">http://jbeckwith.com/?p=370</guid>
		<description><![CDATA[After months of hard work by the WebMatrix team, it's exciting to introduce the release candidate of WebMatrix 2.  WebMatrix 2 includes tons of new features, but today I want to give an overview of the work we've done to enable building applications with Node.js.  ]]></description>
			<content:encoded><![CDATA[<p><img src="http://jbeckwith.com/wp-content/uploads/2012/06/title-header.png" alt="WebMatrix 2 + Node.js = love" /></p>
<p>After months of hard work by the WebMatrix team, it&#8217;s exciting to introduce the release candidate of WebMatrix 2.  WebMatrix 2 includes tons of new features, but today I want to give an overview of the work we&#8217;ve done to enable building applications with Node.js.  </p>
<p>If you want to skip all of this and just get a download link (it&#8217;s free!), <a href="http://bit.ly/LG7gs8" target="_blank">here you go</a>.</p>
<h1>How far we have come</h1>
<p>
Less than a year ago, I was working at Carnegie Mellon University, trying to use Node.js with ASP.NET for real time components of our online learning environment.  Running Linux inside of our customers&#8217; data centers was a non-starter, and running a production system in cygwin was even less ideal.  Developing node on Windows wasn&#8217;t exactly easy either &#8211; if you managed to get node running, getting NPM to work was near impossible.  Using node in an environment favorable to Windows was more than an up hill battle.
</p>
<p>
In the last 12 months since I&#8217;ve joined Microsoft, we&#8217;ve seen various partnerships between Joyent and Microsoft, resulting in new releases of node and npm to support Windows, and a <a href="https://www.windowsazure.com/en-us/develop/nodejs/" target="_blank">commitment to Node on Windows Azure</a>.     We&#8217;ve worked together to build a better experience for developers, IT administrators, and ultimately, the users who use our systems.
</p>
<p>
One of the results of that work is a vastly improved experience for building applications with Node.js on Windows Azure.  Glenn Block on the SDK team has done a <a href="http://codebetter.com/glennblock/2012/06/07/windowsazure-just-got-a-lot-friendlier-to-node-js-developers/" target="_blank">fabulous write up</a> on the ways Microsoft is making Azure a great place for Node.js developers.  As our favorite VP Scott Guthrie says on his blog, <a href="http://weblogs.asp.net/scottgu/archive/2012/06/07/meet-the-new-windows-azure.aspx" target="_blank">meet the new Windows Azure</a>.</p>
<h1>Enter WebMatrix 2</h1>
<p>Today, getting started with node.js is a relatively simple task.  You install node, npm (which is now bundled with the node installers), and get started with your favorite text editor.  There are infinite possibilities, and limitless configurations for managing projects, compiling CoffeeScript &#038; LESS, configuring your production settings, and deploying your apps.  WebMatrix 2 sets out to provide another way to build node.js apps:  everything you need to build great apps is one place.</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/splash.png" rel="lightbox[370]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/splash.png" alt="Welcome to WebMatrix" class="alignnone" style="width:100%"   /><br />
</a></p>
<p>WebMatrix 2 is first and foremost designed for building web applications.  From the start screen, you can create applications using pre-built templates, or install common open source applications from the Web Gallery.  The current set of templates support creating applications with <a href="http://nodejs.org/" target="_blank">Node.js</a>, <a href="http://php.net/" target="_blank">PHP</a>, and (of course) <a href="http://www.asp.net/web-pages" target="_blank">ASP.NET Web Pages</a>.  Out of the box, WebMatrix 2 includes three templates for Node.js:</p>
<ul>
<li>Empty Node.js Site</li>
<li>Express Site</li>
<li>Express Starter Site</li>
</ul>
<p>
The empty site provides a very basic example of using an http server &#8211; the same sample that&#8217;s available on <a href="http://nodejs.org" target="_blank">nodejs.org</a>.  The Express Site is a basic application generated using the scaffolding tool in the Node.js framework <a href="http://expressjs.com/" target="_blank">express</a>.  The Node Starter Site is where things start to get interesting.  This boilerplate is <a href="https://github.com/MicrosoftWebMatrix/ExpressStarter" target="_blank">hosted on GitHub</a>, and shows how to implement sites that include parent/child layouts with jade, LESS css, logins with Twitter and Facebook, mobile layouts, and captcha.   When you create a new application using any of these templates, WebMatrix 2 is going to ensure node, npm, and IISNode are installed on your system.  If not, it will automatically install any missing dependencies.  This feature is also particularly useful if you are building PHP/MySQL applications on Windows.
</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/dependencies.png" rel="lightbox[370]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/dependencies.png" alt="WebMatrix installs node, npm, and iisnode" class="alignnone" style="width:100%"   /><br />
</a></p>
<p>The end result of the Node Starter Site is a fully functional application that includes Express, Jade, LESS, chat with socket.io, logins with EveryAuth, and mobile support with jQuery Mobile:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/template.png" rel="lightbox[370]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/template.png" alt="The node starter template" class="alignnone" style="width:100%"   /><br />
</a></p>
<h1>IntelliSense for Node.js</h1>
<p>
One of the goals of WebMatrix 2 is reduce the barrier of entry for developers getting started with Node.js.  One of the ways to do that is to provide IntelliSense for the core modules on which all applications are built.  The documentation we use is actually built from the docs on the <a href="http://nodejs.org/api/" target="_blank">node.js docs site</a>.
</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/moduleIntelliSense.png" rel="lightbox[370]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/moduleIntelliSense.png" alt="WebMatrix provides IntelliSense that makes it easier to get started" class="alignnone" style="width:100%"  /><br />
</a></p>
<p>
In addition to providing IntelliSense for core Node.js modules, WebMatrix 2 also provides code completion for your own JavaScript code, and third party modules installed through NPM.  There are infinite ways to build your application, and the NPM gallery recently <a href="https://twitter.com/JavaScriptDaily/status/203878468205817857" target="_blank">surpassed 10,000 entries</a>.    As developers start building more complex applications, it can be difficult (or even intimidating) to get started.  WebMatrix 2 is making it easier to deal with open source packages:
</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/thirdpartyintellisense.png" rel="lightbox[370]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/thirdpartyintellisense.png" alt="Use third party modules with code completion" class="alignnone" style="width:100%"   /><br />
</a></p>
<h1>Support for Jade &#038; EJS</h1>
<p>
To build a truly useful tool for building Node.js web applications, we decided to provide first class editors for <a href="http://jade-lang.com/" target="_blank">Jade</a> and <a href="http://embeddedjs.com/" target="_blank">EJS</a>.  WebMatrix 2 provides syntax highlighting, HTML validation, code outlining, and auto-completion for Jade and EJS.
</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/jade.png" rel="lightbox[370]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/jade.png" alt="WebMatrix has syntax highlighting for Jade" class="alignnone" style="width:100%"   /><br />
</a></p>
<p>
If you&#8217;re into the whole angle bracket thing, the experience in EJS even better, since it&#8217;s based off of our advanced HTML editor:
</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/moduleIntelliSense.png" rel="lightbox[370]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/ejs.png" alt="WebMatrix has IntelliSense for EJS" class="alignnone" style="width:100%"   /><br />
</a></p>
<h1>The best {LESS} editor on the planet</h1>
<p>So I&#8217;ll admit it &#8211; I&#8217;m a bit of a CSS pre-processor geek.  I don&#8217;t write CSS because I love it, but because I need to get stuff done, and I want to write as little of it as possible.  Tools like <a href="http://lesscss.org/" target="_blank">LESS</a> and <a href="http://sass-lang.com/" target="_blank">Sass</a> provide missing features for programmers in CSS like variables, mixins, nesting, and built in common functions.  </p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/less.png" rel="lightbox[370]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/less.png" alt="Write LESS with validation, formatting, and IntelliSense"  class="alignnone"  /><br />
</a></p>
<p>The LESS editor in WebMatrix not only provides syntax highlighting, but also provides LESS specific validation, IntelliSense for variables and mixins, and LESS specific formatting.  Most node developers are going to process their LESS on the server using the npm module, but if you want to compile LESS locally, you can use the <a href="http://extensions.webmatrix.com/packages/OrangeBits/" target="_blank">Orange Bits compiler</a> to compile your CSS at design time.  </p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/sass.png" rel="lightbox[370]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/sass.png" alt="WebMatrix provides syntax highlighting for Sass" class="alignnone"  /><br />
</a></p>
<h1>CoffeeScript Editor</h1>
<p>
In the same way LESS and Sass make it easier to write CSS, <a href="http://coffeescript.org/" target="_blank">CoffeeScript</a> simplifies the way you write JavaScript.  WebMatrix 2 provides syntax highlighting, code outlining, and completion that simplifies the editing experience.  If you want to use CoffeeScript without compiling it on the server, you can use the <a href="http://extensions.webmatrix.com/packages/OrangeBits/" target="_blank">Orange Bits compiler</a> to compile your CoffeeScript into JavaScript at design time.
</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/coffeescript.png" rel="lightbox[370]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/coffeescript.png" alt="WebMatrix and CoffeeScript" class="alignnone"   /><br />
</a></p>
<h1>Mobile Emulators</h1>
<p>
Designing applications for mobile can&#8217;t be an afterthought.  WebMatrix 2 is trying to make this easier in a couple of ways.  First &#8211; the visual templates (in this case the Node Starter Template) is designed taking advantage of responsive layouts in the main StyleSheet:</p>
<ul>
<li><a href="https://github.com/MicrosoftWebMatrix/ExpressStarter/blob/master/public/stylesheets/style.less" target="_blank">styles.less</a></li>
</ul>
<p>This is great if you don&#8217;t need to change the content of your site, but is lacking for more complex scenarios.  To get around that, the node starter template uses a piece of connect middleware to detect if the user is coming from a mobile device, and sends them to a mobile layout based on jQuery Mobile (more on this in another post).  For individual views, there is a convention based system that allows you to create {viewName}_mobile.jade views which are only loaded on mobile devices.
</p>
<p>
It gets even better.  What if you need to see what your site will look like in various browsers and mobile devices?  WebMatrix 2 provides an extensibility model that allows you to add mobile and desktop browsers to the run menu:
</p>
</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/emulators.png" rel="lightbox[370]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/emulators.png" alt="WebMatrix shows all of the browsers and emulators on your system" class="alignnone"  /><br />
</a></p>
<p>Today, we offer a Windows Phone emulator, and iPhone / iPad simulators.  In the future we&#8217;re looking for people to build support for other emulators *coughs* android *coughs*, and even build bridges to online browser testing applications:</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/iphone.png" rel="lightbox[370]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/iphone.png" alt="Test your websites on the iPhone simulator" class="alignnone"   /><br />
</a></p>
<h1>Extensions &#038; Open Source</h1>
<p>
A code editing tool is only as valuable as the developers that commit to the platform.  We want to achieve success with everyone, and grow together.  As part of that goal, we&#8217;ve opened up an extensibility model that allows developers to build custom extensions and share them with other developers.  The extension gallery is available online (more on this to come) at <a href="http://extensions.webmatrix.com" target="_blank">http://extensions.webmatrix.com</a>.  We&#8217;re planning to move a bunch of these extensions into GitHub, and the NodePowerTools extension is the first one to go open source:</p>
<ul>
<li><a href="https://github.com/MicrosoftWebMatrix/NodePowerTools" target="_blank">Node Power Tools</a></li>
<li><a href="https://github.com/JustinBeckwith/OrangeBits" target="_blank">OrangeBits Compiler</a></li>
</ul>
<p>In the coming months you&#8217;ll start to see more extensions from Microsoft, and more open source.
</p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2012/06/extension-gallery.png" rel="lightbox[370]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2012/06/extension-gallery.png" alt="Build extensions and share them on the extension gallery" class="alignnone" style="width:100%"   /><br />
</a></p>
<h1>Everyone worked together</h1>
<p>I want to make sure I thank everyone who helped make this release happen, including the WebMatrix team, Glenn Block, Claudio Caldato, our Node Advisory board, Isaac Schlueter, and everyone at Joyent.  For more information, please visit:</p>
<ul>
<li><a href="http://bit.ly/LG7gs8" target="_blank">WebMatrix on Microsoft.com</a></li>
<li><a href="https://twitter.com/#!/webmatrix" target="_blank">WebMatrix on Twitter</a></li>
<li><a href="https://github.com/MicrosoftWebMatrix" target="_blank">WebMatrix on GitHub</a></li>
<li><a href="http://webmatrix.uservoice.com" target="_blank">WebMatrix on UserVoice</a></li>
<li><a href="http://www.microsoft.com/web/post/how-to-use-the-nodejs-starter-template-in-webmatrix" target="_blank">WebMatrix and Node on Microsoft.com</a></li>
<li><a href="http://codebetter.com/glennblock/2012/06/07/windowsazure-just-got-a-lot-friendlier-to-node-js-developers/" target="_blank">Windows Azure just got a lot friendlier to node.js developers</a></li>
<li><a href="http://vishaljoshi.blogspot.com/2012/06/announcing-webmatrix-2-rc.html" target="_blank">Vishal Joshi&#8217;s blog post</a></li>
</ul>
<h2>Enjoy!</h2>
]]></content:encoded>
			<wfw:commentRss>http://jbeckwith.com/2012/06/07/node-js-meet-webmatrix-2/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
		<item>
		<title>Building a user map with SignalR and Bing</title>
		<link>http://jbeckwith.com/2011/10/12/building-a-user-map-with-signalr-and-bing/</link>
		<comments>http://jbeckwith.com/2011/10/12/building-a-user-map-with-signalr-and-bing/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 05:03:11 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Bing]]></category>
		<category><![CDATA[featured]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[SignalR]]></category>

		<guid isPermaLink="false">http://jbeckwith.com/?p=320</guid>
		<description><![CDATA[This post examines the asynchronous connection abstraction library for ASP.NET, SignalR.  It takes some of the best ideas from node/socket.io, and adds them to the .NET stack.  ]]></description>
			<content:encoded><![CDATA[<p><a href="http://signalrmap.apphb.com"  target="_blank"><img src="http://jbeckwith.com/wp-content/uploads/2011/10/signalrheader.png" alt="" title="Building a user map with SignalR and Bing" width="430" height="290" class="alignnone size-full wp-image-326" /></a></p>
<p>Building asynchronous real time apps with bidirectional communication has traditionally been a very difficult thing to do.  HTTP was originally designed to speak in terms of requests and responses, long before concepts of rich media, social integration, and real time communication were considered staples of modern web development.  Over the years, various solutions have been hacked together to solve this problem.  You can use plugins like flash or silverlight to make a true socket connection on your behalf &#8211; but not all clients support plugins.  You can use long polling to manage multiple connections via HTTP &#8211; but this can be tricky to implement, and can eat up system resources.  The <a href="http://dev.w3.org/html5/websockets/" target="_blank">Web Socket standard</a> promises to give web developers a first class socket connection, but browser support is spotty and inconsistent.  </p>
<p>Various tools across multiple stacks have been release to solve this problem, but in this post I would like to talk about the first real asynchronous client/server package for ASP.NET:  <a href="https://github.com/SignalR/SignalR" target="_blank">SignalR</a>.  SignalR allows .NET developers to change the way we think about client/server messaging:  instead of worrying about implementation details of  web sockets, we can focus on the way communication flows across the various components of our applications.  </p>
<h2>This sounds familiar: socket.io with node.js</h2>
<p>Over the last year or so, <a href="http://nodejs.org/" target="_blank">node.js</a> has burst onto the scene as a popular stack for building highly asynchronous applications.  The event driven model of JavaScript, paired with a community of inventive developers, led to a platform well suited for these needs.  The package <a href="http://socket.io/" target="_blank">socket.io</a> provides what I have found to be the missing piece in the comet puzzle:  a front and back end framework that just makes sockets over the web work.  No more building flash applications to attempt opening connections over various ports.  No more poorly implemented long polling solutions.  Most importantly, socket.io made web sockets just plain easy to use:</p>
<pre class="brush: xml; title: ;">
&lt;script src=&quot;/socket.io/socket.io.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
&lt;/script&gt;
</pre>
<p>Node.js and socket.io paved the way for a series of new tools and frameworks across multiple stacks that enable developers to have a first class client/server messaging experience.  Node.js and socket.io are wonderful tools &#8211; but let&#8217;s get back to focusing on SignalR.</p>
<h2>Two ways to build apps with SignalR</h2>
<p>There are two ways you can go about setting up the server for SignalR.  If you want a low level experience, you can add a &#8216;PersistentConnection&#8217; class along with a custom route.  This will give you basic messaging capabilities, suitable for many apps.  Straight from the <a href="https://github.com/SignalR/SignalR" target="_blank">SignalR github</a>, here is an example:</p>
<pre class="brush: csharp; title: ;">
using SignalR;

public class MyConnection : PersistentConnection {
    protected override Task OnReceivedAsync(string clientId, string data) {
        // Broadcast data to all clients
        return Connection.Broadcast(data);
    }
}
</pre>
<p>This works well if you&#8217;re dealing with simple messaging &#8211; the other model SignalR supports is the &#8216;hub&#8217; model.  This is where things start to get interesting.  Using hubs, you can invoke client side functions from the server, and server side functions from the client.  Here&#8217;s another example from the documentation:</p>
<p>Here is the server:</p>
<pre class="brush: csharp; title: ;">
public class Chat : Hub {
    public void Send(string message) {
        // Call the addMessage method on all clients
        Clients.addMessage(message);
    }
}
</pre>
<p>And the client:</p>
<pre class="brush: xml; title: ;">
&lt;script type=&quot;text/javascript&quot;&gt;
$(function () {
    // Proxy created on the fly
    var chat = $.connection.chat;

    // Declare a function on the chat hub so the server can invoke it
    chat.addMessage = function(message) {
        $('#messages').append('&lt;li&gt;' + message + '&lt;/li&gt;');
    };

    $(&quot;#broadcast&quot;).click(function () {
        // Call the chat method on the server
        chat.send($('#msg').val())
            .fail(function(e) { alert(e); }) // Supports jQuery deferred
    });

    // Start the connection
    $.connection.hub.start();
});
&lt;/script&gt;

&lt;input type=&quot;text&quot; id=&quot;msg&quot; /&gt;
&lt;input type=&quot;button&quot; id=&quot;broadcast&quot; /&gt;

&lt;ul id=&quot;messages&quot;&gt;
&lt;/ul&gt;
</pre>
<p>I chose the high level API, because well&#8230; it&#8217;s just cool.  For a wonderful break down of the differences between these two methods, check out <a href="http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx" target="_blank">Scott Hanselman&#8217;s post on the topic</a>.   </p>
<h2>Lets build something!</h2>
<p>One of the common examples of using these frameworks is a chat room:  it has all of the touch points that are otherwise difficult to implement.  How do we know when someone joins the room?  What about sending a message? What if I want to send a message to multiple people?  This is a perfect example of how client/server messaging over the web can make our lives easier.  The SignalR folks have a live sample of this application running on their <a href="http://chatapp.apphb.com/" target="_blank">demo site</a>. With the chat idea done, I decided to combine two tools into one project:  a user map.  I want to maintain a map that uses a pushpin for every user on the page.  As users come, a new pushpin will be added in their location in real time.  As they leave, the pushpin will be removed.  Before we dive into the code, check out the demo at <a href="http://signalrmap.apphb.com/" target="_blank">http://signalrmap.apphb.com/</a>.  If no one is in the room, you can slightly randomize your position by using the &#8220;random flag&#8221; at <a href="http://signalrmap.apphb.com/?random=true" target="_blank">http://signalrmap.apphb.com/?random=true</a>.  This will allow you to use multiple browser windows and watch the system add location push pins.  </p>
<h2>Building the client</h2>
<p>The client of SignalRMap includes a Bing map, and some JavaScript to interact with the back end.  I used <a href="http://www.asp.net/mvc/mvc3" target="_blank">ASP.NET MVC 3</a> for this example, but this will work just fine with a web form.  To start, we need to include a few script files:</p>
<pre class="brush: xml; title: ;">
&lt;script charset=&quot;UTF-8&quot; type=&quot;text/javascript&quot; src=&quot;http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery-1.6.4.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery.signalR.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;@Url.Content(&quot;~/signalr/hubs&quot;)&quot;&gt;&lt;/script&gt;
</pre>
<p>The first thing we are including here is the Bing Maps JavaScript SDK &#8211; this will do all of the heavy lifting for our maps.  The SignalR client is dependent upon JavaScript, so we need to include it along with our SignalR reference.  Finally, we include the &#8216;hubs&#8217; functionality into our application, linking our client and server side methods.</p>
<p>After including our scripts, connecting to a hub is crazy awesome easy:</p>
<pre class="brush: jscript; title: ;">
// create the connection to our hub
var mapHub = $.connection.mapHub;

// define some javascript methods the server side hub can invoke

// add a new client to the map
mapHub.addClient = function (client) {
	addClient(client);
	centerMap();
	var pins = getPushPins();
	$(&quot;#userCount&quot;).html(pins.length)
};

// start the hub
$.connection.hub.start(function () {
	// after the hub has started, get the current location from the browser
	navigator.geolocation.getCurrentPosition(function (position) {

		// create the map element on the page
		mappit(position);

		// notify the server a new user has joined the party
		var coords = isRandom ? createRandomPosition(position) : position.coords;
		var message = { 'user': '', 'location': { latitude: coords.latitude, longitude: coords.longitude} };
		mapHub.join(message);
	});
});
</pre>
<p>There are a few things going on here.  First, we reference our connection to the hub created on the server (note: the connection has not been established yet).  Notice the mapHub.addClient method &#8211; this method will be exposed in a way such that it can be invoked from the server.  *scratches head* &#8211; this is a neat concept.  After defining methods which can be invoked from the server, we start the connection to the hub.  Once the connection is established, we get the browser&#8217;s current location, and send that location back to the server. That&#8217;s about it.  Remember how simple it was to use socket.io?  Here we have the same experience.    There&#8217;s a little more client script here to handle managing the map component.  For the full client source for the application, check out my <a href="https://github.com/JustinBeckwith/SignalRMap" target="_blank">github</a>.</p>
<h2>Server side code</h2>
<p>As mentioned above, I chose to take the &#8216;hubs&#8217; route for my application.  One of the nice things about using a hub is that it doesn&#8217;t require any custom routing &#8211; just create a class that extends &#8216;Hub&#8217;, and you&#8217;re set.  In this example, I&#8217;m storing a persistent list of the clients connected to the application (obviously, this method will only work with a single web server).  As users show up at the site, they send their current position to the server.  The new MapClient is broadcasted to all of the connected clients, and the new client is given the master list of clients:</p>
<pre class="brush: csharp; title: ;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SignalR.Hubs;

namespace SignalRMap
{
	public class MapHub : Hub, IDisconnect
	{
		private static readonly Dictionary&lt;string, MapClient&gt; _clients = new Dictionary&lt;string, MapClient&gt;();

		public void Join(MapClient message)
		{
			_clients.Add(this.Context.ClientId, message);
			Clients.addClient(message);
			this.Caller.addClients(_clients.ToArray());
		}

		public void Disconnect()
		{
			MapClient client = _clients[Context.ClientId];
			_clients.Remove(Context.ClientId);
			Clients.removeClient(client);
		}

		/// &lt;summary&gt;
		/// model class for the join message. I tried to use dynamic here, but it didn't work.
		/// &lt;/summary&gt;
		public class MapClient
		{
			public string clientId { get; set; }
			public Location location { get; set; }

			public class Location
			{
				public float latitude { get; set; }
				public float longitude { get; set; }
			}
		}
	}
}
</pre>
<p>And that&#8217;s it!  SignalR figured out what types of communication my browser supports, managed the tunnel, and just made the connection work.  Enjoy!</p>
<ul>
<li><a href="http://signalrmap.apphb.com/?random=true" target="_blank">View the demo</a></li>
<li><a href="https://github.com/JustinBeckwith/SignalRMap" target="_blank">Download the source code</a></li>
<li><a href="https://github.com/SignalR/SignalR" target="_blank">SignalR on GitHub</a></li>
<li><a href="http://www.bingmapsportal.com/ISDK/AjaxV7" target="_blank">Bing Maps SDK</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://jbeckwith.com/2011/10/12/building-a-user-map-with-signalr-and-bing/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Using MSBuild to deploy your AppFabric Application</title>
		<link>http://jbeckwith.com/2011/07/20/using-msbuild-to-deploy-your-appfabric-application/</link>
		<comments>http://jbeckwith.com/2011/07/20/using-msbuild-to-deploy-your-appfabric-application/#comments</comments>
		<pubDate>Wed, 20 Jul 2011 21:24:10 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AppFabric]]></category>
		<category><![CDATA[Automated Builds]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[MSBuild]]></category>

		<guid isPermaLink="false">http://jbeckwith.com/?p=311</guid>
		<description><![CDATA[I wrote a blog post for the MSDN AppFabric Blog! Using MSBuild to deploy your AppFabric Application]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-314" title="azure3" src="http://jbeckwith.com/wp-content/uploads/2011/07/azure3.png" alt="" width="150" height="150" /></p>
<p>I wrote a blog post for the MSDN AppFabric Blog!</p>
<p><a href="http://blogs.msdn.com/b/appfabric/archive/2011/07/20/using-msbuild-to-deploy-your-appfabric-application.aspx" target="_blank"><br />
Using MSBuild to deploy your AppFabric Application<br />
</a></p>
]]></content:encoded>
			<wfw:commentRss>http://jbeckwith.com/2011/07/20/using-msbuild-to-deploy-your-appfabric-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FRINK! &#8211; the Reddit client for tablets</title>
		<link>http://jbeckwith.com/2011/04/18/frink/</link>
		<comments>http://jbeckwith.com/2011/04/18/frink/#comments</comments>
		<pubDate>Mon, 18 Apr 2011 18:01:11 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Projects]]></category>
		<category><![CDATA[Adobe Flex]]></category>
		<category><![CDATA[BlackBerry]]></category>
		<category><![CDATA[featured]]></category>
		<category><![CDATA[PlayBook]]></category>

		<guid isPermaLink="false">http://jbeckwith.com/?p=277</guid>
		<description><![CDATA[Frink! is a mobile client for the web site <a href="http://www.reddit.com" target="_blank">Reddit</a>. It is designed specifically to be used with tablets, taking advantage of gestures in a unique user interface.  ]]></description>
			<content:encoded><![CDATA[<p><img src="http://jbeckwith.com/wp-content/uploads/2011/04/frink-header1.png" alt="" title="FRINK!" width="430" height="290" class="aligncenter size-full wp-image-290" /></p>
<p>Frink! is a mobile client for the web site <a href="http://www.reddit.com" target="_blank">Reddit</a>. It is designed specifically to be used with tablets, taking advantage of gestures in a unique user interface.  Right now the app is available in the BlackBerry App World:</p>
<p><a href="http://appworld.blackberry.com/webstore/content/38838?lang=en" target="_blank">http://appworld.blackberry.com/webstore/content/38838?lang=en</a></p>
<p>After the code has a little time to settle, I plan on releasing the app to the Android Market as well.  The entire project is open source, and available on my <a target="_blank" href="https://github.com/JustinBeckwith/frink">GitHub</a></p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2011/04/comments.png" rel="lightbox[277]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2011/04/comments.png" alt="" title="comments on a post"  style="width:100%"  class="aligncenter size-full wp-image-280" /><br />
</a></p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2011/04/post-details.png" rel="lightbox[277]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2011/04/post-details.png" alt="" title="post details"  style="width:100%"  class="aligncenter size-full wp-image-281" /><br />
</a></p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2011/04/subreddits.png" rel="lightbox[277]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2011/04/subreddits.png" alt="" title="subreddits"  style="width:100%"  class="aligncenter size-full wp-image-283" /><br />
</a></p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2011/04/posts.png" rel="lightbox[277]"><br />
<img src="http://jbeckwith.com/wp-content/uploads/2011/04/posts.png" alt="" title="posts"  style="width:100%"  class="aligncenter size-full wp-image-282" /><br />
</a><br />
For more information, here are a bunch of links that talk about the project:</p>
<ul>
<li>
Frink! on the web: <a target="_blank" href="http://frinkapp.com">http://frinkapp.com</a>
</li>
<li>
Frink! on Reddit: <a target="_blank" href="http://www.reddit.com/r/frinkapp">http://www.reddit.com/r/frinkapp</a>
</li>
<li>
Frink! on Twitter: <a target="_blank" href="http://twitter.com/frinkapp">http://twitter.com/frinkapp</a>
</li>
<li>
Frink! on GitHub: <a target="_blank" href="https://github.com/JustinBeckwith/frink">https://github.com/JustinBeckwith/frink</a>
</li>
<li>
Frink! at BlackBerry App World: <a target="_blank" href="http://appworld.blackberry.com/webstore/content/38838?lang=en">http://appworld.blackberry.com/webstore/content/38838</a>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://jbeckwith.com/2011/04/18/frink/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>The Cause and Effect of Google&#039;s h.264 Decision</title>
		<link>http://jbeckwith.com/2011/01/20/google-h264/</link>
		<comments>http://jbeckwith.com/2011/01/20/google-h264/#comments</comments>
		<pubDate>Thu, 20 Jan 2011 03:44:25 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Opinion]]></category>
		<category><![CDATA[Apple]]></category>
		<category><![CDATA[Chrome]]></category>
		<category><![CDATA[featured]]></category>
		<category><![CDATA[Firefox]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[H.264]]></category>
		<category><![CDATA[Safari]]></category>
		<category><![CDATA[Video]]></category>
		<category><![CDATA[VP8]]></category>
		<category><![CDATA[WebM]]></category>

		<guid isPermaLink="false">http://jbeckwith.com/?p=227</guid>
		<description><![CDATA[How do the internal workings of a browser that was released only two years ago have an enormous ripple effect on the future of streaming media on the internet? Last week Google announced on their chromium blog that they&#8217;re dropping support for the h.264 codec, in favor of the open source Ogg Theora and WebM/VP8 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://jbeckwith.com/2011/01/20/google-h264/h264-header-2/" rel="attachment wp-att-262"><img src="http://jbeckwith.com/wp-content/uploads/2011/01/h264-header1.png" alt="" title="The Cause and Effect of Google&#039;s H.264 Decision" width="383" height="166" class="aligncenter size-full wp-image-262" /></a></p>
<p>How do the internal workings of a browser that was released only two years ago have an enormous ripple effect on the future of streaming media on the internet?  Last week Google announced on their chromium blog that they&#8217;re <a href="http://blog.chromium.org/2011/01/html-video-codec-support-in-chrome.html"> dropping support for the h.264 codec</a>, in favor of the open source <a href="http://www.theora.org/">Ogg Theora</a> and <a href="http://blog.webmproject.org/">WebM/VP8</a> codecs.  This is yet another snag in the messy attempt to unify the playback of video in HTML 5, as we now find the #2 and #3 most popular browsers lacking support for what currently is likely the most ubiquitous encoding format.  So how did we get here?</p>
<h3>The browser wars are back</h3>
<p>
After years of IE 6 and Firefox being the only real browsers around, the browser wars have exploded again.  For the first time since Netscape 4.7 roamed the earth, Internet Explorer has dropped below 50% in the market share.  That leaves a lot of space for the likes of Firefox, Chrome, Safari, and Opera.  Well, maybe not Opera.  The interesting thing in this graph is the dominance of Firefox, and the growth of Chrome.  That leaves ~42% of the current desktop browser market with no H.264 native playback, and ~96% of the next desktop browser market that supports WebM (assuming everyone here upgrades to the latest version of course).  </p>
<div id="browser-ww-monthly-200912-201012" width="600" height="400" style="width:600px; height: 400px;"></div>
<p><!-- You may change the values of width and height above to resize the chart -->
<p>Source: <a href="http://gs.statcounter.com/?PHPSESSID=9ni6qaq0p0vdrb4bjtfm6l51i4">StatCounter Global Stats &#8211; Browser Market Share</a></p>
<p><script type="text/javascript" src="http://www.statcounter.com/js/FusionCharts.js"></script><script type="text/javascript" src="http://gs.statcounter.com/chart.php?browser-ww-monthly-200912-201012"></script></p>
<p>What&#8217;s scary about this is the proliferation of new browsers through mobile and embedded devices.  As time goes on, iOS, Android, and RIM are going to eat more and more of those beautiful hits on our Google Analytics dashboards.  While iOS is currently ahead in terms of volume, <a href="http://blog.nielsen.com/nielsenwire/online_mobile/apple-leads-smartphone-race-while-android-attracts-most-recent-customers/">Android is catching up</a>.  Quickly. </p>
<p><a href="http://jbeckwith.com/wp-content/uploads/2011/01/smartphone-os-nov2010.png" rel="lightbox[227]"><img src="http://jbeckwith.com/wp-content/uploads/2011/01/smartphone-os-nov2010.png" alt="" title="Smartphone Market 2010" width="575" height="369" class="aligncenter size-full wp-image-243" /></a></p>
<p>As the homogeneity of the browser market continues to disappear, the likelihood that all browsers will support the same native HTML 5 playback goes down quickly.  So why did Google do this?</p>
<h3>Is YouTube making money yet?  How about now?  Now?</h3>
<p>
In 2006 Google acquired YouTube for $1.65 billion in stock.  The costs of running a video delivery site are sky high, and the sale price certainly turned a lot of heads.  While I&#8217;ve heard a lot of people question the acquisition, there are estimates that YouTube may be <a href="http://mediamemo.allthingsd.com/20100305/another-youtube-revenue-guess-1-billion-in-2011/">generating as much as 1 billion a year in revenue</a> moving forward.  Don&#8217;t be mistaken, YouTube is a vital piece to controlling advertising in the streaming media market.  They will protect their investment, and continue to grow other revenue streams to support the costs of the platform.  One of the ways I look for Google to do this is through providing a channel to charge for premium or protected content.  MPEG LA makes providing content encoded using H.264 free until 2016 &#8211; given the content is available freely to the end user.  The moment you charge for the delivery of that content, you are subject to a delivery fee of 2% revenue per title, up to a maximum $5 million cap.  While I don&#8217;t think the $5 million is a huge deal to Google, it&#8217;s an enormous deal for smaller software shops, startups, integrators, and hardware companies that want to stream and decode video from YouTube on their sites or devices.  This model will eventually have a stifling effect on innovation in the streaming media market, which directly affects Google&#8217;s YouTube line of business.  This pretty easily explains why Google <a href="http://blog.streamingmedia.com/the_business_of_online_vi/2009/08/googles-acquisition-of-on2-not-a-big-deal-heres-why.html">purchased the VP8 codec from On2 for $106.5 million</a>.  </p>
<p>In the short term, this decision isn&#8217;t going to cause a whole lot of impact.  Even if most browsers did support HTML 5, which they don&#8217;t, most of the video out there today is in H.264 format.  All of the hardware devices that support decoding are using H.264.  This is a decision that pays dividends 5 years down the road.  Estimates have YouTube receiving as much as <a href="http://www.youtube.com/t/fact_sheet">24 hours of content per minute</a>, which is dizzying to think about.  No matter how you store it, that&#8217;s a ton of storage space.  More and more of the content being added to the system is in high definition, so that makes the problem even bigger.  Now add the fact that you need to encode your content in two different formats over the long haul, and you have a huge problem.  I want to know &#8211; will Google have the stones to yank H.264 support from YouTube all together?</p>
<h3>Where does this leave everyone?</h3>
<p>
As mentioned above, I don&#8217;t think this changes a lot in the short term.  Here is where I see the big players ending up with the change:</p>
<ul>
<li><b>Adobe</b> &#8211; Adobe comes out of this situation in great shape.  This pretty much just guarantees that flash isn&#8217;t going anywhere for a couple of years, and they&#8217;ve already <a href="http://blogs.adobe.com/flashplatform/2010/05/adobe_support_for_vp8.html">announced support for VP8</a>.</li>
<li><b>Microsoft</b> &#8211; Microsoft, who doesn&#8217;t have a horse in this race anymore, has already announced VP8 support for Internet Explorer 9.</li>
<li><b>Google</b> &#8211; Google gets to protect their YouTube and VP8 investments, while promoting innovation through an open standard.</li>
<li><b>Mozilla</b> &#8211; Firefox will remain relevant, given their VP8 support in version 4.  I doubt the Mozilla Foundation had any intentions of paying MPEG LA $5 million.</li>
<li><b>Apple</b> &#8211; If Google drops H.264 support of YouTube (which won&#8217;t happen for a long time), Apple with have their hand forced into supporting WebM. Until that happens, this is a total mystery to me.</li>
</ul>
<p>Overall, I think Google&#8217;s decision is a good thing for content developers and innovators.  Not everyone agrees.  For a few dissenting opinions on this, check out:</p>
<ul>
<li>
<a href="http://www.zdnet.com/blog/hardware/chromes-love-of-webm-and-hatred-of-h264-has-nothing-to-do-with-youtube/11021">Chrome&#8217;s love of WebM and hatred of H.264 has nothing to do with YouTube</a>
</li>
<li>
<a href="http://arstechnica.com/web/news/2011/01/googles-dropping-h264-from-chrome-a-step-backward-for-openness.ars/">Google&#8217;s dropping H.264 from Chrome a step backward for openness</a>
</li>
</ul>
<p>
And of course, I want to know what you think.  So lets start some discussions!</p>
]]></content:encoded>
			<wfw:commentRss>http://jbeckwith.com/2011/01/20/google-h264/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bootstrapping image based bookmarklets</title>
		<link>http://jbeckwith.com/2010/12/28/bootstrapping-image-based-bookmarklets/</link>
		<comments>http://jbeckwith.com/2010/12/28/bootstrapping-image-based-bookmarklets/#comments</comments>
		<pubDate>Tue, 28 Dec 2010 02:12:09 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[featured]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery UI]]></category>

		<guid isPermaLink="false">http://jbeckwith.com/?p=113</guid>
		<description><![CDATA[In this article I am going to go through the code I used to bootstrap my bookmarklet script, and discuss some of the interesting challenges I experienced along the way.]]></description>
			<content:encoded><![CDATA[<p><img src="http://jbeckwith.com/wp-content/uploads/2010/12/featured.png" alt="" title="featured" width="430" height="290" class="alignnone size-full wp-image-153" /></p>
<p>Over this holiday break I had the interesting opportunity to write a bookmarklet for a friend who runs a comic based website.   Instead of just manipulating the currently loaded page, the bookmarklet needed to send a list of images to another site.  Often when writing <a title="Wikipedia - Bookmarklets" href="http://en.wikipedia.org/wiki/Bookmarklet" target="_blank">bookmarklets</a>, we tend to only think of loading our code in the context of a HTML content page.  How often do you test your bookmarklets when the browser is viewing an image?  In this article I am going to go through the code I used to bootstrap my bookmarklet script, and discuss some of the interesting challenges I experienced along the way.</p>
<p>To get started with this code, I used a fantastic <a href="http://www.smashingmagazine.com/2010/05/23/make-your-own-bookmarklets-with-jquery/" target="_blank">article</a> by <a href="http://www.smashingmagazine.com/author/tommy-iamnotagoodartist/" target="_blank">Tommy Saylor</a> of <a href="http://www.smashingmagazine.com/" target="_blank">Smashing Magazine</a>.  It gave me a good start, but certainly left a lot of details out, and in my case, caused a lot of bugs.</p>
<h3><span style="text-decoration: underline;">Bookmarklet Architecture</span></h3>
<p>That&#8217;s right:  we should talk about architecture before diving right into our JavaScript.  When writing a bookmarklet, it&#8217;s generally a good idea to keep as much code out of the actual bookmark as possible.  This is where &#8216;bootstrapping&#8217; comes into play:  we will simply use our bookmark as a piece of code that actually loads the core bits of our JavaScript.  There are actually two reasons why this is a good idea:</p>
<ul>
<li>Different browsers have various max-lengths of bookmarks.  Keep in mind that a bookmarklet is kind of an accidental feature.  I think the average max length works out to around 2000 characters, but some browsers (like Internet Explorer 6) have limits as low as 508 characters.</li>
<li>Users are unlikely to be bothered into refreshing your bookmarklet.  Once somebody bookmarks your code, how are they going to get updates?  It&#8217;s much easier if your bookmarklet simply loads a JavaScript file from a static URL.  This way we can update the code in the back whenever we want.</li>
</ul>
<p>After our bootstrapper loads the script we created, any external libraries will be loaded.  For example, I used jQuery and jQuery UI for my most recent project.  After the dependencies are loaded, we will then execute our main code.</p>
<p>Another thing to keep in mind when you&#8217;re building your bookmarklet is how the site behaves after the function is disabled.  For example, if your bookmarklet gives all images on the site a red border, what happens when the user no longer wishes to use the bookmarklet?  For this reason, I tend to create a cleanup method that allows our bookmarklet changes to be undone, and leaves the script in a state that can later be used again.</p>
<h3><span style="text-decoration: underline;">The bootstrap code</span></h3>
<p>For the purposes of this bookmarklet, I needed to write a piece of code that would interact with a standard HTML page and it&#8217;s images, or interact with a page that was a single loaded image. For that reason, the first thing we need to do is determine what type of page we&#8217;re dealing with.  If the page is HTML, we can insert a script.  If the page is an image, we need to behave differently.  While I found that Firefox and WebKit both generated a HTML container to render image pages, their behavior surrounding script events of these pages were too inconsistent to be depended upon.</p>
<p><img src="http://jbeckwith.com/wp-content/uploads/2010/12/firebug.png" alt="" title="Image url firebug output" width="501" height="635" class="alignnone size-full wp-image-155" /></p>
<p>Here is a formatted example of what my a href tag JavaScript looks like:</p>
<pre class="brush: jscript; title: ;">
//
// &lt;a&gt; tag href javascript
//
javascript:(function() {
	if( (document.contentType &amp;&amp; document.contentType.indexOf('image/')&gt;-1)
		||/.png$/.test(location.href)
		||/.jpg$/.test(location.href)
		||/.jpeg$/.test(location.href)
		||/.gif$/.test(location.href))
		{
			location.href='http://jbeckwith.com/bookmarklet/';
		}
		else if (!window.main) {
			document.body.appendChild(document.createElement('script'))
				.src='http://jbeckwith.com/my-bookmarklet.js';
		}
		else {
			main();
		}
	})();
</pre>
<p>After tidying up our script, and adding the surrounding tag, here is a final rendered output of our code, I came up with the following:</p>
<pre class="brush: xml; title: ;">
&lt;!--
    &lt;a&gt; tag example
--&gt;
&lt;a href=&quot;javascript:(function(){if((document.contentType&amp;&amp;document.contentType.indexOf('image/')&gt;-1)||/.png$/.test(location.href)||/.jpg$/.test(location.href)||/.jpeg$/.test(location.href)||/.gif$/.test(location.href)){location.href='http://jbeckwith.com/bookmarklet/';}else if(!window.main){document.body.appendChild(document.createElement('script')).src='http://jbeckwith.com/my-bookmarklet.js';}else{main();}})();&quot;&gt;It's a bookmarklet!&lt;/a&gt;
</pre>
<h3><span style="text-decoration: underline;">Loading jQuery and jQueryUI</span></h3>
<p>Now that the bootstrapper is created, I am going to focus the rest of the article on the external JavaScript file that contains the meat of the code.  With the script I wrote, I needed to use a good deal of visual effects.  I am already comfortable with <a href="http://jquery.com/" target="_blank">JQuery</a>, so I chose to use it as my JavaScript framework:</p>
<pre class="brush: jscript; title: ;">
//
// create javascript libraries required for main
//
if (typeof jQuery == 'undefined') {
	// include jquery
	var jQ = document.createElement('script');
	jQ.type = 'text/javascript';
	jQ.onload=getDependencies;
	jQ.onreadystatechange=function() {
		if(this.readyState=='loaded' || this.readyState=='complete') {
			getDependencies();
		} // end if
	};
	jQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
	document.body.appendChild(jQ);
} // end if
else {
	getDependencies();
} // end else
</pre>
<p>If you look at the example in the Smashing Magazine article, you will notice a couple of differences.  We need to add an event for onreadystatechange to handle Internet Explorer.  I found that IE inconsistently set the readyState of the script object to &#8216;loaded&#8217; or &#8216;complete&#8217; in various parts of the DOM, so as a rule I check for both.  If you don&#8217;t make this change, IE will never notify the script that jQuery is finished loading.  </p>
<p>Secondly, I have added the getDependencies() method to manage loading required scripts (in addition to jQuery).  Since I am depending heavily on a few jQuery UI components, I needed to load both an external JavaScript file and an external CSS file:</p>
<pre class="brush: jscript; title: ;">
//
// getDependencies
//
function getDependencies() {

	// make sure jqueryUI is loaded
	if (!jQuery.ui) {

		// get the link css tag
		var jQCSS = document.createElement('link');
		jQCSS.type = 'text/css';
		jQCSS.rel= 'stylesheet';
		jQCSS.href = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css';
		document.body.appendChild(jQCSS);

		// grab jquery ui
		var jQUI = document.createElement('script');
		jQUI.type = 'text/javascript';
		jQUI.src = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js';
		jQUI.onload=getDependencies;
		jQUI.onreadystatechange=function() {
			if(this.readyState=='loaded' || this.readyState=='complete') {
				getDependencies();
			} // end if
		};
		document.body.appendChild(jQUI);
	} // end if
	else {
		main();
	} // end else
} // end getDependencies function
</pre>
<p>In this case, I&#8217;m really only waiting on jQuery and jQuery UI to load.  If there were more dependent scripts, I would likely create an array of scripts that need to be loaded, and check all of their completion every turn through the getDepenencies method.  </p>
<h3><span style="text-decoration: underline;">Embedding Styles</span></h3>
<p>With the supporting code written, we&#8217;re now ready to work on our main method.  This is where bookmarklets really are different based on your task.  In my case, I&#8217;m creating a visual element on the page, complete with styles to match the target site.  This works pretty much as expected, with a single caveat:  any style definitions you create must be at the very bottom of your appended script.  Internet Explorer has a nasty habit of inconsistently handling styles and scripts when appended to the DOM.  For some reason beyond my understanding, appended style definitions, whether via script or ajax calls, only work if they are at the very bottom of the appended code.  This is fantastically fun to figure out on your own, so hopefully I&#8217;ve saved you some trouble.</p>
<pre class="brush: jscript; title: ;">
//
// main
//
function main() {
	// only do this the first time the bar is loaded on the page
	if ($(&quot;#myBar&quot;).length == 0) {
		// append the styles and bar

		var barHtml =	&quot;&lt;div id='myBar'&gt;\
							&lt;div id='myBar-main' class='dragOff'&gt;\
								&lt;span id='myBar-thumbs'&gt;&lt;/span&gt;\
								&lt;span id='myBar-text'&gt;drag images to the mainbar&lt;/span&gt;\
								&lt;span id='myBar-buttons'&gt;\
									&lt;a href='#' id='doneLink'&gt;done&lt;/a&gt;\
									&lt;a href='#' id='cancelLink'&gt;cancel&lt;/a&gt;\
								&lt;/span&gt;\
							&lt;/div&gt;\
						&lt;/div&gt;\
						&lt;style type='text/css'&gt;\
								#myBar {color: #FFFFFF; font-size: 130%; font-weight: bold; left: 0; position: fixed; text-align: center; top: 0; width: 100%; z-index: 99998; display: none; }\
								#myBar-main {border-bottom: 3px solid #000000; padding: 7px 0;}\
								#myBar-buttons { display: block; float: right; margin-right: 20px; }\
								#myBar-buttons a,\
								#myBar-buttons a:visited,\
								#myBar-buttons a:link,\
								#myBar-buttons a:active,\
								#myBar-buttons a:hover\
									{ padding: 4px; font-size: 0.7em; border: 2px solid #008600; background-color: #00cb00; color: #FFFFFF; text-decoration: none; }\
								#myBar-thumbs img { padding-left: 2px; padding-right: 2px; cursor: hand; }\
								.my-hover { border: 3px solid #4476b8 }\
								.dragOff { background-color: #4476b8; }\
								.dropHover{background-color: #FF0000; border: 1px dashed #e5a8a8;}\
								.dragActive {background-color: #759fd6}\
								.dropHighlight{border: 1px solid #000000;}\
								.dragHelper {z-index: 99999; border: 1px solid #000000;}\
							&lt;/style&gt;&quot;;
		$(&quot;body&quot;).append(barHtml);
</pre>
<p>This code simply creates a formatted div and adds it to the top of the page.  </p>
<h3><span style="text-decoration: underline;">Cleaning up the mess</span></h3>
<p>If you look at the generated HTML above, you&#8217;ll notice that I include a cancel link.  I like to give the user the option to cancel out of using the current bookmarklet, and even relaunch the bookmarklet without issue.  So when you&#8217;re done, make sure to test closing and re-launching the code.  I suggest keeping all of your elements on the page, and simply hiding them from the user:</p>
<pre class="brush: jscript; title: ;">
		//
		// myBar close evnet
		//
		$(&quot;#cancelLink&quot;).click(function(e) {
			// hide the bar
			$(&quot;#myBar&quot;).fadeOut(750);

			// remove any img classes or handlers
			$(&quot;img&quot;).removeClass('my-hover').unbind().draggable(&quot;destroy&quot;);

			// reset the thumbnail span
			$(&quot;#myBar-thumbs&quot;).html('');

			// reset the text
			$(&quot;#myBar-text&quot;).html(&quot;drag images to the mybar&quot;);
		});
</pre>
<p>And for now, that&#8217;s it.  For the source to this project, visit my <a href="https://github.com/JustinBeckwith/Chogger-Bookmarklet" target="_blank">GitHub</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://jbeckwith.com/2010/12/28/bootstrapping-image-based-bookmarklets/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
