Friday 4 March 2016

Starting an AngularJS Project with Visual Studio

When I decided to start an AngularJS project many decisions come into my head. One of the first decisions is the IDE and the technologies that will be used. There are many good IDE on the market that supports JavaScript and some AngularJS. The ones that support AngularJS can be with extensions or native. They range from the simplest which are Sublime Text, BracketsAtom, etc. to the most complete as WebStorm and Visual Studio. On the other hand you can use any server side language, I personally prefer .Net, Node.js andRuby. There are many criterias for choosing your optimal development environment, from the customer and the company to personal preferences.  This article is about starting a project with AngularJS on .Net and its several alternatives, I won’t write any code, this is just a technical tutorial that will save you a couple hours on internet and investigation.

Table of Content

  1. Setup Visual Studio
    1. General Plugins
    2. Templates
    3. Intellisense
  2. Choosing kind of app
    1. Using AngularJS inside an MVC layout or a Web Form
    2. AngularJS and WebAPI
    3. AngularJS and externals RESTful endpoints
  3. Projects and AngularJS architecture
    1. Shared project
    2. AngularJS arquitecture
  4. Testing
    1. Karma
    2. Chuztpah
    3. Resharper
    4. TeamCity
  5. Build
    1. Plugins
    2. Pulling all together
  6. Conclusion

Setup Visual Studio

There are many versions of Visual Studio available in the website of Microsoft, all off them are good products from the online version to theUltimate version.  Almost every version of this product is paid except Visual Studio Express and the recent Community Edition. Once you choose Visual Studio as the IDE for programming with AngularJS, you must configure it for a better experience. Several of these configurations need plugins, some of them will be helpful for general purposes and some others are only for develop with AngularJS.  Below I ‘ll be showing how to set up a better environment to develop with AngularJS.

General plugins

No matter what kind of web project you will start using Visual Studio, you should use at least one of the next plugin/extension for Visual Studio. There are plugins more related with AngularJS but I prefer not to use any of them.

Web Essentials – link

This extension let us perform common task very fast and add many web development features missing by default in Visual Studio. It is one of the best in the market.
output_9M4OtV

Productivity Power Tools – link

It is an extension pack that brings powerful tools to improve the productivity. The features are focused on personalize Visual Studio and not the code that we write.

CssCop – FxCop for Stylesheet – link

CSSCop enable the widely used CSS Lint tool behind the scenes. This tool complement the css best practice suggestions of Web Essentials extension.

Mexedge Stylesheet – link

This Visual Studio extension allows you to visualize in a tree view form the structure of your css files right into your Solution Explorer, I don’t use it anymore because I use LESS in all my recent projects.

MultiEditing – link

This is a simple extension that enable the multiline editing pressing the ALT key. I love this feature in Sublime Text.

Task Runner Explorer – link

This extension allows you execute any Grunt/Gulp task or target inside Visual Studio by adding a Task Runner Explorer window.

Package Intellisense – link

An NPM and Bower package intellisense in Visual Studio that let you View, Install, Uninstall and Update packages.

Snippetizer – link

Let you build snippets, collect them and of course use it.

Visual Studio Spell Checker – link

A simple extension that correct your spelling.

File Nesting – link

In order to keep a project as flat as possible and not to create more folders to organize your project, this extension will let you order files by its relation.

Templates

Sometime we want to start a project from a template having the basics for build your solution without rewrite the same structure all the time. Visual Studio has several templates to build an ASP.NET MVC application, and let you download more online. Among the online templates there are several that include AngularJS and have a previous structure that help us with the new projects. The best templates are:
templates

Intellisense

Maybe one of the difference between a good IDE and an awesome IDE is the intellisense. Since Visual Studio 2008 it has intellisense for Javascript and with the lasts version the intellisense has been improved, that is not the case of AngularJS, and other javascript frameworks. The improve related to javascript framework that modify the HTML with custom tags, is to remove the validation of custom elements, polymer-elements and attributes. In order to provide Visual Studio with an intellisense for AngularJS you have several ways described below:

Web Essentials 2013

This tool has several features to improve both intellisense to the edit HTML to Javascript editor, for example any HTML element with a ng-controllerattribute has a Smart Tag for generating the .js controller file.
WebEssential

Resharper

If you have purchased a Resharper license you have the possibility to use all the benefits with Javascript and with Visual Studio, it also has an extension that includes support for AngularJS. This support includes code completion of AngularJS attributes when editing HTML files and others features. You can find more information here. If you want to enable the extension go to Resharper in the Menu bar, click on Extension Manager and search AngularJS.
Resharper Extension

Modifying the HTML 5 XSD Schema File

Visual Studio has a XML Schema definition language for Html 5 that define the structure and data types for this standard. If you modify this file and add all the built in AngularJS directives, you’ll be able to use it when you are in the HTML editor. This file is usually located in:
C:\Program Files (x86)\Microsoft Visual Studio (x.0)\Common7\Packages\schemas\html\commonHTML5Types.xsd
where “x” is the version of VS. This an example of how you could see the file after the modification I mentioned before:

Referencing *.js files

When Visual Studio 2012 was released, a new Javascript editor came with a powerful intellisense. There are many ways to extend the intellisense for Javascript, some automatically and others manually like reference javascript files with triple slash, creating a _references.js file or creating an {libraryname}.intellisense.js.You can find more information about this topic in the blog of Mad Kristensen or in the page about Javacript Intellisense in MSDN.
There are a repository in GitHub of John Bledsoe called “JavaScript Intellisense for AngularJS Components in Visual Studio” that mix some of the above techniques applies to Angular JS. You can download here.
JavaScript Intellisense for AngularJS Components in Visual Studio

kindHeader

Choosing kind of app

When you are close to start an AngularJS project in Visual Studio, it is a good moment to stop and think how AngularJS would interact and live inside an ASP.NET web application. This decision depend of the client, the requirements of the project and many others factors. I like to separate it in several categories, each one show the relation between ASP.NET MVC or Web Form and the client code. The categories are:

Using AngularJS inside an MVC layout or a Web Form

Possible this is the common way, and the natural way of the developer that has a working background with Legacy.NET  and ASP.NET MVC. This is a nice way to mix the best of both world, the client side and the server side. To start a project with this characteristics you just need to create a project with a template by default or use an online template like the previously seen.
vsmvctemplates
Once completed the creation of the project you need to add AngularJS to the project manually, with Nuget or with another package manager like Bower. At this point you can build your application without any problem using both AngularJS and ASP.NET. A common problem with this way comes when you try to pass some data from ASP.NET to AngularJS, this can be accomplish passing the data directly -throw the Controller in the case of MVC- to AngularJS with the ng-init directive or creating services/factories/value/constant/provider to get the data, calling with the service $http or $resource to a controller, or the best way is calling a Web API. Another possible problem is to build a full SPA because when you implement routing with AngularJS you can’t route with razor views or aspx pages, so you have to use plain html except for the index page.

AngularJS and WebAPI

Another way to use AngularJS and ASP.NET is build an entire SPA and communicate only with web services. Therefore, in this kind of application, ASP.NET won’t render any pages, all the pages in our app will be plain html that communicate with our app through web services created with WebAPI. This type of projects are more decoupling -with the technology use in the server side- that the previously and we can build a full SPA without many problems.  A simple solution structure could be:
webapi
The upper level of the solution would have the projects, this could be theRepository project, the LogicDataProvidersModelsInterfaces, etc. and the Website project. Going deeper in the Website project you can find a common WebAPI structure, more simple that one with ASP.NET MVC or legacy.NET. It would have the WebAPI controllers, some standards folder likeApp_Start, and a folder that would wrap our AngularJS application, for example App.

AngularJS and externals RESTful endpoints

This last type of application in Visual Studio doesn’t use nothing of ASP.NET, it just use Visual Studio. A quickly advantage is that the project is fully portable and it is completely independent of the server side. A project like this can be develop in many IDEs and can emulate the external endpoint with a WebAPI located in others project of our solution.
projectHeader

Projects and AngularJS architecture

How to order your solution is sometime complicated at the first moments of a project and essential for the scalability. It’s very important have a solution well organize, I mean:
  1. decoupling,
  2. applying separation of concerns (SoC),
  3. applying single responsibility principle too,
  4. our code located easily,
  5. try to don’t repeat yourself,
  6. identify code at a glance,
  7. keep the structure as flat as we can,
  8. and others.
Of course that the organization of the code depend completely of the project but there are good principles that applied to all projects and they are a plus for the quality of your code. You can find more information with “Key Principles of Software Architecture” by MSDNSOLIDGRASPGoF Pattern and many others web resources. This is a one-way road, once you start using patterns and better ways of programming you don’t want to move back ever.
Some tips about the organization of an AngularJS project in Visual Studio is try to take advantage of the “projects” in a solution and have a “project” for every SPA. Others project could be the model, the repository, the logic, the authentication, etc.

Shared project

A common problem when you are building a SPA is how will share resources the different part of the application. I mean, how will share libraries, javascript files, html files, image files the backend, frontend, maybe a specific version to mobile or another special separated version of the application. In this case a good solution is to have a Shared project and keep there all the common files, including the libraries downloaded with nuget and bower. To add the common files to each project Visual Studio let use direct links in this way:
Right click over the destination folder of the file > Select Add > click on Existing Item… > Look at the file to import > click on the right arrow(drop down) of Add button and select Add as Link.
addlink
After this step, you’ll have a direct link to the file but you won’t have the physical file, so if you drag the file to the editor -and it is a Javascript file- Visual Studio will create a script that aim to the shared file in the shared project. If you want the file locally you can write an MSBUILD script that will copy the linked file when you compile. With this trick you once you modify the shared file if you compile every link in will updated instantaneously.  Below an example of the MSBUILD sentences:

AngularJS arquitecture

After choose how you’ll organize the projects in your solution, is turn of the AngularJS project itself. Try to say the best file organization is very hard, because it depend of how large the project is, and what is our pretensions. It’s not a good idea create a complex structure when the project will not grow too much.
There are five common ways of structuring the files in an AngularJS project, not the only ones but sure the most used:

Monolithic files

This structure propose create folders for the different type of files. It’s very optimized for small sites where the amount of files does not exceed ten files. An example of this type of project is the PhoneCat Tutorial in the website of AngularJS.

Monolithic folders

A clear disadvantage of the previous structure in a medium size project is that if you have more than ten controllers and directives you have to find in a file with more than 300 lines and it is really uncomfortable. Following the single responsibility principle you can have a file by functionality and with this little improve you can find any controller or directive at a glance. If you use Yeoman to build a scaffolding of AngularJS with the angular-generator a structure very similar to this is created. Here is the proposed solution:

Organize by feature

Instead of grouping files be their type, the recomendation here is to group by feature. Features are a high level of abstraction that contain all the logic, templates, styles, etc. It is like a wrapper of the common functionality of the files. It is a mapping between what you see on the screen to the source files that make it happen. For example if I am looking the profile page then I expect to be able to find all the code for it in the profile feature. An organization like this decouple even more the application and give a straightforward logic order.

Organize by module

AngularJS let you define modules where this modules can contain controllers, services, directives, etc. If you follow the last pattern of organization – as feature -, you can wrap each feature in a module. The advantage of doing this is that the you can reuse this module in others projects, this is a common way of doing 3rd-party AngularJS code. Another advantage of organize by module is that you can routing by module instead of have a huge central routing for all the application. There are usually a file named “app.js” in each module where the routing its configured. An example of an structure is very similar to previous pattern but with the module configuration files.

Mixing all – Ordering by module by feature

When you have a huge project before your eyes it’s a good idea mix all the previous architectures to a better organization. The higher level of this architecture is to organize by module, inside each module you can organize by module again, by feature or by monolithic folder. The purpose of this architecture is kept as tidy as possible a large project without losing meaning or flatness.
To cover beyond architecture, means in the syntax, I recommend reading theAngularJS style guide by Papa John and the other one by Todd Motto. These kind of guides provide consistency through good practices.
testingHeader

Testing

The testing is an essential part of every project so in this chapter you will see different ways of configure an environment of testing in Visual Studio.

Karma

The AngularJS team provide a tool called Karma that it’s a test runner for unit testing and take all the frustration out of configure a properly test runner and run your code in several real browsers.
Install Karma it’s very easy. We just need install it and configure it. In the site of Karma you can find information and how to install it.
Once that it is installed you can use it external to Visual Studio, however there are a few plugins out there that could help you with this task. I’ll let you the links with the instructions:

VS Adapter for Google’s Karma Test Runner – link

After installed the plugin and ran for first time Karma you would be able to use the Visual Studio Test Explorer Window to handle our tests.
Screenshot

KarmaVs – link

This plugin give you the Karma feedbacks through the Output Window.
Untitled2

Chutzpah

If you want to manage and run your javascript unit test via the Visual Studio, Chutzpah is good choice. Chutzpah (hutz-pah) is a unit test runner that support QUnit, Jasmine and Mocha testing frameworks. It has an adapter for the Visual Studio Unit Test Explorer that enable run the tests inside a folder or run a quick test in the test explorer.
To install Chutzpah you must follow this steps:
1- Open Tools -> Extensions and Updates, click on Online left-tabs and look for Chutzpah, then install Chutzpah Test Adapter for the Test Explorer and Chutzpah Test Runner Context Menu Extension
chutzpah
2- Install jasmine.js from NuGet
jasmine
3- Download the mock module of AngularJS to the project
4- Write the code referring all files need it with the triple slash method
references
If you follow these steps, once you open the test explorer of Visual Studio you will find all the javascript test that you have written, and you will be able to run test with the context menu of the mouse.

Resharper

If you use ReSharper (R#) with your Visual Studio you can use the resharper test runner instead other like Karma or Chutzpah. All you need to do is download jasmine and include it as reference in your tests. To configure it, go to the ReSharper options and navigate to Tools -> Unit Testing -> JavaScript Test and ensure that ‘Enable Jasmine support’ is checked, set the Jasmine version too. If you want to use a specified browser to test you can set it here, however, ReSharper give you the opportunity to use PhantomJS to run the tests too. PhantomJS let you test without open a browser window every time you want to run your test suite. To use it, download the PhantomJS executable and place it in somewhere of your preferency, once that the executable its placed set it in the options.
resharperOpt
Now you should be able to see your tests in the ReSharper Unit Test Explorer window:
testResharper

TeamCity

In progress…
buildHeader

Build

ASP.NET 4.5 has some techniques to improves load time by reducing the number of requests to the server and reducing the size of requested assets. This techniques is called Bundling and Minification are very easy to use, but maybe you want more flexibility and write your custom optimization or even download third parties code and include it in your code. If you are thinking in this next level of optimization then you should work with Grunt or Gulp. It doesn’t really matter which tool you use, you will get more control and quality over your final product.

Plugins

There are a few plugin able to use Grunt/Gulp in Visual Studio that let you interact with the tools.

Grunt Launcher

This plugin let you launch grunt tasks from the solution explorer. When right clicking on a gruntfile you will see a new submenu listing all your options. It’s compatible with bower and gulp even though its name.
gruntlauncher

TRX – Task Runner Explorer

This extention lets you execute any Grunt/Gulp task or target inside Visual Studio by adding a new Task Runner Explorer window. One of best things are the Before/After Build feature.
bindings

Putting all together

When you have the configuration file and every module active, and all the work run perfectly; the next step is run it automatically when you have to test it or the application go out to production. I like to attach this behavior to the Release mode, so when I change from Debug to Release mode and compile the solution, automatically Grunt/Gulp create a optimized version of my product. This approach it’s very simple, you just need to include in the Pre-build/Post-build event command line an “if” condition that verify if the solution are in Release mode, and then run Grunt. Remember that if you have a Continuous Integration server, Grunt or Gulp must be installed in the server. Below, I show you an example of how to do it.
final

Conclusion

Well, I hope this article has been helpful, and you apply at least one of the different techniques shown it here. If you have any doubt don’t forget write a comment, and I’ll try to respond as soon as possible.

1 comment:

  1. I’m not sure exactly why but this weblog is loading very slow for me. Is anyone else having this issue or is it a problem on my end? I’ll check back later on and see if the problem still exists.
    voyance gratuite mail

    ReplyDelete

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...