Client-Side Productivity with Browser Link

Browser Link Banner

As you know Angular is a client-side framework – it’s home is in the browser. Visual Studio, on the other hand, has traditionally shined as the server development environment. Well there is a technology that attempts to bridge the gap between Visual Studio and the browser – it’s called Browser Link.

This post details Browser Link’s best features and discusses why you should use it. You will learn how to set it up when using static files for your Angular project and you will be prepared for some limitations and trade offs you may encounter. Overall you will find that Browser Link is a compelling and under-utilized tool in Visual Studio that you should add to your tool belt.

What is Browser Link?

Browser Link is a feature introduced with Visual Studio 2013 that runs when you press F5 to build, deploy, and run your project. It leverages the two-way communication of SignalR to send information from Visual Studio to the client and back.

While Visual Studio-to-client communication may seem trivial, this is a rich canvas on which to build truly time-saving features. For instance, think about how much time you spend in the browser’s F12 developer tools. What if you can link the work that you do in these tools to the code in Visual Studio? How many times do you duplicate CSS changes that you make in the browser by copying them to the correct file in Visual Studio? Browser Link makes this type of workflow obsolete by communicating changes between both the client-side and server-side development environments.

Setting Up Browser Link

There isn’t much to know to setup Browser Link. The two main requirements are that Browser Link is enabled and the project is running in debug mode. To enable Browser Link, press the Browser Link button’s drop-down arrow and press Enable Browser Link.

Enable Browser Link

Unless configured otherwise, debug mode is enabled by default when you run your project with F5. However to ensure you are running in debug mode, select Start Debugging in Visual Studio’s Debug menu.

Because many Angular applications use static HTML files instead of .cshtml or .aspx files, there is one additional configuration that needs to be added to the web.config file to enable Browser Link with static HTML files:

<system.webServer>
    <handlers>
        <add name="Browser Link for HTML" path="*.html" verb="*"
            type="System.Web.StaticFileHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
            resourceType="File" preCondition="integratedMode" />
    </handlers>
</system.webServer>

For more on enabling Browser Link, read the corresponding ASP.NET documentation.

Finally, you should download and install the Web Essentials Visual Studio extension. The download and installation instructions are on the Web Essentials website.

Browser Refresh

The basic Browser Link scenario is Browser Refresh. This feature comes out-of-the-box and allows you to trigger the browser to refresh from Visual Studio. For example, you make a change to your client-side code in Visual Studio. Then for anything that doesn’t require a recompile, you would typically go to your browser and refresh the page in order to verify your changes. With Browser Link running however, you simply press the Browser Link refresh button or use the CTRL + ALT + ENTER key combination to save your files and simultaneously trigger the browser to refresh right from within Visual Studio.

Because Browser Link uses web standards, this works with any browser including mobile browsers on devices and in emulators. You can also trigger multiple browsers. If you want to check that your CSS animation runs across all of your application’s supported browsers, one button press or key combination refreshes all of them at the same time.

Web Essentials and Browser Link

Some of the most interesting Browser Link uses are found in the popular Visual Studio add-in Web Essentials. Web Essentials is a sweeping collection of tools. You should take a look for yourself when you have the chance – it’s good stuff. There are several features to discuss related to Browser Link.

Once you have installed the Web Essentials add-in and enabled Browser Link, there is a new Web Essentials toolbar that appears at the bottom of the page in your browser when you run your Visual Studio project.

Browser Link toolbar

This toolbar is displayed or hidden using the CTRL key. The toolbar provides several interesting pieces of functionality including two of the most useful: Save F12 changes and Inspect.

Have you ever spent time adjusting the CSS properties of an element in the browser to get just the right position, font size, or layout? The typical workflow is often then to copy the changes you made, if you remember them, into Visual Studio, save the files, and then refresh the browser to double check that you copied the CSS correctly. By using the Save F12 changes button, Web Essentials uses Browser Link to send the DOM changes back to Visual Studio and add them to the correct CSS selector in the correct file – it’s almost like magic.

Another feature is an easier way to find the source code for browser elements. In the past you may have found an element in the browser’s developer tools and then searched your project for the element’s id or class. Now, you can press the Inspect button on the Web Essentials toolbar to enable inspection mode. Once this mode is enabled, click on the element you are interested in and Visual Studio jumps to that markup in the appropriate code file – again, almost like magic.

Pro tip: hover over the buttons in the Web Essentials toolbar to see its keyboard shortcut.

Limitations and Trade-Offs

While the Browser Link technology enables some very useful scenarios, you should be aware of some issues that you may see. First, you are limited in Visual Studio by debug mode. Things like renaming or moving files can’t be done while running in this mode. Also, Browser Link sends a lot of network traffic so if you are using the browser’s network profiler, you may want to shut Browser Link off temporarily.

Furthermore, Web Essentials is often a proving ground for functionality before moving it into Visual Studio. You may encounter some functionality that doesn’t quite work as you expected. The key here is to try out the tooling on a non-critical project first to develop a comfort level and/or be sure to use source control or make a backup of your project. I use the features detailed in this post and find them to be stable and helpful. If for some reason the tooling doesn’t produce the output you were expecting, using CTRL+Z in Visual Studio to undo the recent changes typically works – but not always.

In Summary

Browser Link is a great Visual Studio feature for web developers. It helps to bridge the divide between development environment and browser tools to increase your productivity. It’s easy to setup and provides compelling features such as Browser Refresh, Save F12 changes, and Inspect. Regardless of whether you are using Angular or other web frameworks, you should give it a try.

The next post will dive into one of the first Angular features that developers use – expressions. They are included in practically every ‘Hello World’ Angular demo and it is important to understand what they are and what their role is in an Angular application – see you then!

Your First Angular Project in Visual Studio

angular-visual-studio

Today is the day. You have been hearing about Angular for a long time now. You have listened to the podcasts, you’ve watched the videos, and you have followed the pre-canned tutorials. Now you are creating your own project. Maybe you have an application idea or you plan to work your way through the documentation. You open up Visual Studio and pause. Which type of project template should you use? What type of back-end should you setup? So many questions.

This post looks to simplify the process and walks through a basic project structure in Visual Studio designed for quick setup and a solid foundation for separation of concerns. The structure aims for simplicity yet some of the recommendations may not be intuitive for the average ASP.NET developer. Angular is a client-side framework and therefore much of the ceremony performed to use ASP.NET for server-side development is unnecessary.

This walk through is for Visual Studio 2013. If you don’t have it, download the community edition (it’s FREE) and get the latest updates. Also install the Web Essentials extension to get the latest web development tooling for Visual Studio. If you have seen Visual Studio 2015, it introduces a new project structure that aids with client-side development. Even though this project structure is aimed at Visual Studio 2013, it should make it is easy to migrate to Visual Studio 2015 when the time comes.

Also, this post doesn’t cover build tools for bundling, minification, and testing even though Visual Studio supports these scenarios. Look for posts on these topics in the future.

Choosing the Project Template

This walkthrough uses a web application project as opposed to a web site project. This is part personal preference and part pragmatism. If you are significantly more comfortable with web site projects, go head and use them. It doesn’t make a significant difference for the purpose of this post.

Using a web application project is not straightforward, however. The tricky part is how the default templates setup things you don’t need – mainly everything specific to ASP.NET.

In the world of client-side frameworks, there is a much cleaner separation of client and server. There is generally no need to create .aspx or .cshtml files in order to render views on the server. Much of the rendering logic in these files can be done in Angular with static HTML files. There may be reasons to use server-rendered views for specific scenarios but start out considering that you don’t need server-rendered views.

“But what about data?” you say. Start out by using static .json files on the file system or hard code collections in your JavaScript. If you need to persist data, there are various in-browser technologies to save what you have done. Eventually yes, you will need to create a back-end but not for starting a basic Angular project.

Now it’s time to create the project. Go ahead and create an ASP.NET Web Application project.

create-first-vs-project

Press OK and this brings you to the dialog where you choose a template and select the features for your application. Choose the Empty template and uncheck all of the ASP.NET features.

create-empty-vs-project

Press OK to create the project. You see the project is indeed empty.

empty-structure

If you press F5 to run the project, you will get a 403 Forbidden error from IIS because there is nothing for you to access.

There is no need for server-side controllers, views or routes at this time. To start, add an index.html file to the root of your project, type Hello World in the body, hit F5 and you will see your friendly message in the browser.

Adding Angular

In order to write an Angular app, you need to reference the Angular JavaScript library. You can go to the Angular website and download it or reference it from the CDN (content delivery network). However, Visual Studio has the NuGet package manager to easily download the scripts and add it to your solution.

Note: in Visual Studio 2015, client-side dependencies will typically be loaded via client-side package managers as opposed to NuGet.

To load the Angular scripts from NuGet, right click on the solution and select ‘Manage NuGet Packages for Solution…’ from the dropdown. This displays the NuGet dialog. Search for “angularjs” and find the listing for AngularJS Core. There are other packages but this one provides the base Angular framework from the AngularJS Team (so it says). Click Install, select your web project, click OK, then Close to exit the dialogs and NuGet adds the Angular script files to your solution.

nuget-script-folder

Now create a script tag to reference the Angular script in your index.html file.

<script src="Scripts/angular.min.js"></script>

Creating a Basic Angular App Structure

Much of what is recommended here comes from John Papa’s information in this blog post and in his style guide. If you are going beyond this basic structure, reading the source material will give you tips to scale your application architecture.

First, start by adding an app folder to the root of your web project. Within the app folder, add two files: app.module.js and main.js.

The app.module.js file houses a single application-level module for your application. In this example, your application has an application-level module that loads the other modules of the application. The purpose of adding app.module.js as a separate file is to introduce the concept that modules, controllers, services, directives, views, etc. should be defined in their own files. Of course this is negotiable but it’s a good place to start. The contents of the app.module.js file should have the following contents.

(function() {
    'use strict';

    angular.module('app', []);

})();

This example uses an IIFE (immediately-invoked function expression) to immediately execute this code and also to encapsulate its scope. This pattern is used with every module. Also, notice the use of 'use strict'. This triggers modern browsers to run the JavaScript in strict mode. It is optional but it can help you avoid coding problems and many linters such as JSLint complain when it’s not included. The call to angular.module registers the module with the Angular framework.

In the main.js file, create a controller. In John Papa’s blog post, controllers do not use the word ‘controller’ in the file name. At first, I thought this was to save keystrokes, but he makes a good point about how this works with routing. However, there are numerous instances in Angular tutorials where ‘controller’ or ‘ctrl’ are used in the naming (including in John Papa’s style guide) so make the best decision for your projects – just be consistent. Here is the code for the main controller.

(function () {
    'use strict';

    angular
        .module('app')
        .controller('Main', main);

    function main() {
        var vm = this;
        vm.food = 'pizza';
    }

})();

In this IIFE, the controller is registered with the app module. An argument could be made to create a main module with which to associate the controller but being that this is the only controller in the project, this can be left out. Once the project grows in complexity, you should consider registering the controllers with feature-level or section-level modules and leave the application-level app module for registering these various sub-modules (read more in the style guide).

The function main is the controller itself. This controller is configured to use the controllerAs syntax. Again, John Papa details the benefits in his style guide. From the perspective of writing the controller, the big notable is that the properties and methods that you apply to scope are defined on this instead of an injected $scope parameter. Most examples I have seen online for Angular use $scope so this may be new to you. In addition, notice the use of the variable vm to capture the scope. This practice helps to avoid any confusion if/when you define nested functions also using the this keyword.

Finally, take a look at the index.html view. Here is the code.

<!DOCTYPE html>

<html ng-app="app">
<head>
    <title></title>
</head>
<body ng-controller="Main as vm">

    <input type="text" ng-model="vm.food" placeholder="Enter food" />

    <p>Sriracha sauce is great with {{vm.food}}!</p>

    <script src="Scripts/angular.min.js"></script>
    <script src="app/app.module.js"></script>
    <script src="app/main.js"></script>

</body>
</html>

First you see the ng-app directive set to the app module to bootstrap the application. On the body tag you see the use of the controller as syntax in the view. Something to note, the use of the name vm in the view has no correlation to its use in the controller. The two variables can have different names. Next, you see the basic example of using the vm scope with a simple input scenario where the value of the input is bound to the expression vm.food. Finally, all of the scripts are referenced on the page.

After completing these steps, your application structure looks like the following.

final-structure

When you run the application you should be able to pair your favorite food with the infamous Rooster Sauce.

final-interface

Conclusion

To those of you who have been using the full breadth of ASP.NET over the years, using static HTML files may seem like a foreign concept and admittedly the ASP.NET project templates tend to favor server-side views.

However, now you have a project that feels like other ASP.NET projects you have worked on. You are still pressing F5 to startup IIS Express and the HTML and JavaScript editors are the ones that you are used to using.

You also have a starter Angular application with basic separation of concerns. You even have a naming convention to use for your modules and controllers as well.

If you would like to download the finished project, you can do so on GitHub.

In the next post, you will learn about a Visual Studio tool called Browser Link. It provides useful features especially for client-side development but there are some tricks to setting it up with static files. Until then, enjoy experimenting with your new Angular project.