How to Run .NET on Heroku

.NET Core continues Microsoft’s shift towards a more open development philosophy. It is open-source and cross-platform. With a little bit of setup, you can get a .NET Core web app running on Linux-powered Heroku. This guide will walk you through it.

This guide is catered for development on Windows, even though the resulting web app runs on Linux via Heroku. .NET Core (the framework) is cross-platform, but Visual Studio (the IDE) is not… yet. However, there are solutions for running Visual Studio on Mac.

.NET Core and Heroku logos

Prerequisites

Make sure you have all of the following prerequisites ready to go.

Create the Solution

Fire up Visual Studio, then go to File > New > Project.

Navigate to Installed > Templates > Visual C# (or Visual Basic, if that’s your thing) > Web. Select ASP.NET Core Web Application (.NET Core). Pick your Name (I’m using “dot-net-heroku” here) and set Location to the directory you want the solution directory to be created within. Check both Create directory for solution and Create new Git repository. Click OK to proceed.

Visual Studio new project dialog

On the next screen, select Web Application (Web API works too, if that’s what you want). Click OK.

Visual Studio template selection dialog

At this point you have a brand new solution. We’ll need to tweak it a bit, though.

Modify the Solution

Still in Visual Studio, go to View > Other Windows > Package Manager Console. This will give you a console with a PM> prompt. Execute the following command.

Now open up Program.cs for some edits. Near the top, add the following using directive.

Then update the Main() function as seen below.

Your Program.cs should look like mine. With that, the solution is ready for deployment. Now to take care of things on the Heroku side.

Create the Heroku App

Open up your command line terminal of choice and navigate to the solution directory. Make sure you’re logged into Heroku.

Create the Heroku app with whatever name you want.

Now to add the buildpack. I’ve had the best results with noliar’s fork, so that’s what I’m using here.

Finally, set up Git to deploy to Heroku and push.

Give the deployment some time to finish up, and there you have it. Go to http://your-app-name.herokuapp.com/ (with your app name, obviously) and you’ll see your .NET web app running on Heroku. It should look like mine.

Chrome screenshot of a .NET Core web app running on Heroku

What you’re seeing is the default index page for the template we used. At this point you’re ready to delete the default pages and start working on your own.

Bonus: Hooking up to GitHub

You’ve got your .NET web app inside a local Git repo, but maybe now you want to add it to GitHub. Start by creating a new repo. To avoid conflicts, don’t initialize with the readme, license, or .gitignore files (you can add these later).

Creating a new GitHub repo

Back in your terminal, run these commands. Replace “your-username” and “your-repo-name” as appropriate.

If you get a pop-up about security credentials, cancel out of it and enter your credentials in the terminal.

If the terminal won’t accept your credentials, it may be because, like me, you have 2-factor authentication enabled. In this case, create a personal access token with repo access and use it in place of your password.

Closing Remarks

It’s great seeing .NET break out of its Windows-only ecosystem to embrace the more open and cross-platform community of modern web development. Also, big thanks to noliar and all the other contributors for maintaining the .NET buildpack I’m using in this guide.

Motion Detection with JavaScript

I recently gave a talk at RevolutionConf about writing a motion detecting web app with JavaScript. This is basically that talk, but in blog form. Live demos and all the source code are available at the end of this article.

The Premise

I wanted to see what my pets do when I’m away. But I didn’t want a continuous live stream, since that would be pretty boring (they sleep a lot). Instead, I decided to build something that would watch for motion, take a snapshot of anything that happens, then upload the snapshot to Twitter for remote viewing.

Basic flow of motion detection web app

Just for kicks, I decided to do this as a web app, all in JavaScript.

Accessing the Webcam

The first step is to access the webcam. This is actually really easy with WebRTC, which is natively supported by modern browsers… unless your browser is Safari. Boo. Another wrinkle is that WebRTC has some syntax differences from browser to browser, but the adapter.js shim will fix that for you.

Anyway, to grab a stream from a webcam, start with a <video> element in your HTML.

Then add a bit of JavaScript.

This will attempt to grab a 640px by 480px stream from an attached webcam. Users will be prompted to permit access, but assuming they do, the stream will be displayed in the <video> element on the page. Check out this quick demo to see it in action.

Grabbing Still Frames

We need to capture still frames from the streaming video so that we can do motion detection (more on this later) and potentially upload them as images to Twitter. I settled on an interval of 100ms between captures, which is 10 frames per second.

We start by grabbing the <video> element with the stream on it from the page. Then a <canvas> element is created in memory, though you could also have it on the page for display.

A simple setInterval() allows us to capture a new still frame every 100ms. Each capture is drawn onto the <canvas> element by calling drawImage() and passing in the <video> element. It’s smart enough to just draw whatever is visible on the <video> element at that very moment.

Once something is drawn on a <canvas>, you can save it off as an encoded image string. We can use this string later when uploading to Twitter.

Of course, we don’t want to save and upload every still frame we capture, just the ones with motion. Fortunately, <canvas> gives us the tools to detect motion.

Diffing

So, what exactly is “motion”? A video (such as a stream from a webcam) is just a bunch of still images shown in rapid succession. Movement is perceived when there are changes between these images. So to check if motion has occurred between two frames of a video, we check for differences between the two images, also known as “diffing”.

We’ve already covered how to draw images onto a <canvas> from a <video>. By default, drawing something onto a <canvas> just covers up whatever was already there, but this can be changed to show you the differences instead.

Here’s an example of an image drawn on top of another with the aforementioned difference setting. Dark pixels indicate areas with little to no motion. Brighter pixels show areas where something moved (in this case, mostly my cat’s head).

Diff image

Scoring

We can see that motion happened on the <canvas>, but how do we turn this into data that we can programmatically evaluate or “score” for motion? The answer is getImageData(). This function returns an ImageData object that has a data property. This property is a long array of numbers, with every chunk of 4 numbers representing a single pixel (red, green, blue, and transparency).

Pixel data

Remember, when diffing, the brighter pixels indicate more difference which means more motion. So the higher the combined red, green, and blue values of a pixel, the more motion that occurred in that pixel. By scoring every pixel like this, we can determine if values are significant enough to consider a capture as having motion.

Here’s a quick algorithm to do this.

Post-Processing the Diff

Not only can we read pixel data from ImageData.data, we can also write adjustments back to it. By tweaking the pixel data this way and then redrawing it with putImageData(), you can essentially do post-processing on the diff image.

I like doing this to make the diff image monochrome green (set red and blue values to 0) and then amplifying the brightness (multiply green values by some constant). This makes it really easy to see where motion is. It also makes it easier to see the ambient visual noise, in case you need to tweak some threshold values to discern between noise and actual motion.

Diff image with post-processing

On top of that, I like to downscale the diff image to 10% of its original width and height. Even a modest 640px by 480px image is a lot of data (307,200 pixels!) to churn through, so downscaling helps lighten the load. Sure, the image becomes super pixelated, but it’s still plenty enough for the purposes of motion detection.

Diff image downscaled

Throttling

One important thing I haven’t covered is throttling. Without throttling, any continuous motion will cause rapid-fire captures to be saved and uploaded to Twitter, 10 times a second. That’s no good.

There are a couple ways to handle this. This is what I went with.

Sequence for throttling

The important thing is the “chilling” state, which is just a cooldown timer. I also added a “considering” state, during which captures can occur continuously, but only the highest scoring capture is kept and uploaded. Hopefully, the highest scoring capture is the most entertaining capture, since it has the most motion.

The Back-End

Even though all the motion detection is done client-side, we still need a back-end since we’re using the Twitter API (can’t have our secret Twitter API key revealed on the front-end).

I won’t go into specifics about the back-end, since it’s not directly related to motion detection. I’ll just mention that I wrote it in node.js, so it still satisfies my “all in JavaScript” goal.

The Results

You can check out the finished web app for yourself. I call it Diff Cam Feed. It’ll ask you to sign in with Twitter so it can upload to your feed (that’s all it does, nothing shady, I promise).

Diff Cam Feed screenshot

I set it up on my laptop for a few trial runs around my apartment. Results were decent. Just my pets, doing pet things.

Various captures of pets

It also works fine on a Raspberry Pi running Raspbian, after installing UV4L.

Diff Cam Feed on a Raspberry Pi

Then I tried it on an old Android phone I had lying around (Samsung Galaxy S4). It works great, as long as you run it in Firefox. For some reason, Chrome on Android dies after a few minutes.

Diff Cam Feed on an Android phone

Conclusion

Overall, this turned out to be a fun side project. The motion detection looks really cool and isn’t very difficult to do. I made it all open source, so you can check out the code in this GitHub repo.

It’s not hard to imagine other uses for motion detection in a web app. If this interests you, then check out Diff Cam Engine. It wraps up a lot of motion detection stuff for you, so you can kickstart your own project.

Lastly, I’ve set up a website with several demos illustrating the concepts I talked about. Feel free to play around with them and check out the code.

Thanks for reading!

Highlight Text Inside a Textarea

Let’s start with the bad news. You can’t actually highlight text in a <textarea>. Any markup you would add to do so would simply display as plain text within the <textarea>. The good news is, with some carefully crafted CSS and JavaScript, you can fake it.

This article will show you how to pull it off, but if you just want the solution, feel free to go straight to the jQuery plugin: highlight-within-textarea.

Highlight within textarea

Why?

Way back in 2010, I made a site called Regex Storm that would highlight regex matches in a <textarea>, like this. It’s not hard to imagine other applications for this sort of “find and highlight” functionality. 5 years is a long time though, so I decided to revisit the concept and fix it up for modern browsers.

The Plan

The basic idea is to carefully position a <div> behind the <textarea>. JavaScript will be used to copy any text entered into the <textarea> to the <div>. A bit more JavaScript will make that both elements scroll as one. With everything perfectly aligned, we can add markup inside the <div> to highlight text, which will show through the <textarea>, completing the illusion.

A demo should make this all clear. Scroll around and edit the text. Then click Toggle Perspective and edit and scroll some more.

See the Pen Highlight Text Inside a Textarea by Will Boyd (@lonekorean) on CodePen.

HTML

It takes a couple of elements to achieve the layout we need.

The container <div> simply serves as an anchor to position other elements within. The highlights <div> is nested within the backdrop <div>, which may seem like 1 more <div> than we need, but doing it this way fixes some subtle scrolling bugs (which we’ll get to later).

The <mark> tag is the best semantic choice for highlighting text inside the highlights <div>. We’ll be inserting these tags with JavaScript.

CSS

Elements must be laid out with pixel perfection. This can be tricky, as many browsers have very subtle differences that normally aren’t worth caring about, but are very noticeable in this case.

For example, Firefox adds a single pixel of margin to the top and bottom of a <textarea>. And iOS adds a border-radius to <textarea>. So we have to fix these styles (and others I haven’t specifically mentioned).

CSS is used to make text inside the highlights <div> wrap and scroll exactly like the text inside the <textarea>.

It’s also important to set the visibility of things so that our stacked elements display properly together. Remember, the <textarea> sits on top of the highlights <div>.

JavaScript

The JavaScript has 3 main responsibilities.

  1. Keep text in the highlights <div> synced with text in the <textarea>.
  2. Highlight text in the highlights <div> with <mark>.
  3. Make the highlights <div> scroll in tandem with the <textarea>.

Let’s start by binding 2 events.

The input event triggers whenever text in the <textarea> is changed. The callback function takes this text, applies highlights to it, then inserts it into the highlights <div>.

And here’s the applyHighlights() function.

applyHighlights() actually does 2 things. On line 3, it fixes a bug where a trailing carriage return causes the highlights <div> to become misaligned. Then on line 4, it does the actual highlighting by inserting <mark> tags. The regex in this example highlights all capitalized words, but this can be customized.

The scroll callback copies the scroll position of the <textarea> to the backdrop <div>, so that they both scroll in tandem.

Wrap Up

That covers the basic mechanics of (fake) highlighting within a <textarea>. Please note that there are some finer details that this article didn’t discuss and the demo didn’t account for. For the more comprehensive, more bullet-proof solution, check out the highlight-within-textarea jQuery plugin on GitHub.

Browser History

I recently gave a lightning talk about the history of web browsers. 20 slides, auto-advancing, 5 minutes total. It starts with the release of the very first web browser by Sir Tim Berners-Lee in 1990 and culminates with the assembly of the “Big 5” browsers in 2008 (Chrome being the last one to the party). The central theme is about how competition (or lack thereof) has shaped the web.

Video embedded below.

0 comments » Related topics: