Tag Archives: JavaScript

ECMAScript

Hello Angular World (page 7 of 7)

Hello Angular World (from Visual Studio and Local IIS)

Pages: 1, 2, 3, 4, 5, 6, 7

Conclusion

So, we now have an ASP.NET MVC web application which is hosting a simple Hello Angular World App. and in limiting the project size and complexity it should serve as a useful “starter template”. When looking at the project, you will notice two distinct naming conventions, initially I thought this was ugly, however it has proven a useful reminder of which environment or language we are dealing with e.g. TypeScript/JavaScript or C#.

References & Useful Links

Hello.Angular.World
https://github.com/sionjlewis/Hello.Angular.World

Angular2Mvc5Application Visual Studio 2015 Template
https://marketplace.visualstudio.com/items?itemName=Payns75.Angular2Mvc5sampleapplication

Angular 2: Visual Studio 2015 Quickstart
https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html#!#prereq1

Node.js Downloads
https://nodejs.org/en/download/

Visual Studio 2015 Update 3
https://www.visualstudio.com/en-us/news/releasenotes/vs2015-update3-vs

TypeScript 2.0 is now available for Visual Studio https://blogs.msdn.microsoft.com/typescript/2016/09/22/announcing-typescript-2-0/

Download and install TypeScript 2.0 for Visual Studio 2015
http://download.microsoft.com/download/6/D/8/6D8381B0-03C1-4BD2-AE65-30FF0A4C62DA/TS2.0.3-TS-release20-nightly-20160921.1/TypeScript_Dev14Full.exe

TypeScript 2.0 is now available for Visual Studio https://blogs.msdn.microsoft.com/typescript/2016/09/22/announcing-typescript-2-0/

NPM Task Runner
https://marketplace.visualstudio.com/items?itemName=MadsKristensen.NPMTaskRunner

Visual Studio: Package Installer
https://marketplace.visualstudio.com/items?itemName=MadsKristensen.PackageInstaller

Task runners in Visual Studio 2015
https://blogs.msdn.microsoft.com/webdev/2016/01/06/task-runners-in-visual-studio-2015/

TypeScript Playground
http://www.typescriptlang.org/play

Specifics of npm’s package.json handling
https://docs.npmjs.com/files/package.json

How npm handles the “scripts” field
https://docs.npmjs.com/misc/scripts

TypeScript Configuration
https://angular.io/docs/ts/latest/guide/typescript-configuration.html

Angular 2 QuickStart / systemjs.config.js
https://github.com/angular/quickstart/blob/master/systemjs.config.js

ASP.NET MVC: Bundling and Minification
https://www.asp.net/mvc/overview/performance/bundling-and-minification

Pages: 1, 2, 3, 4, 5, 6, 7

Hello Angular World (page 6 of 7)

Hello Angular World (from Visual Studio and Local IIS)

Pages: 1, 2, 3, 4, 5, 6, 7

Hello Angular World from a MVCV View

Now we have an Angular 2 app running in our Local IIS (or IIS Express if you decided to skip that section), let’s build a very simple MVC app to host our Angular 2 app.

Add a Controller

  1. Expand the Angular.World project
  2. Right-click Controller…
  3. Click Add > Controller
  4. Select MVC 5 Controller – Empty
  5. Click Add
  6. Enter HomeController for the Controller name
  7. Click Add

Add a Layout

  1. Expand the Angular.World project
  2. Right-click Views
  3. Click Add > New Folder
  4. Rename the folder Shared
  5. Right-click Shared
  6. Click Add > MVC 5 Layout Page (Razor)
  7. Enter _Layout for the Item name
  8. Click OK
  9. Change the code to match:


Note: At this point you may notice that the @Styles is underlined in red, this is because the project is missing a reference, which we will address soon.

  1. Save and close

Add the _ViewStart View

  1. Expand the Angular.World project
  2. Right-click Views
  3. Click Add > MVC 5 View Page with Layout (Razor)
  4. Enter _ViewStart for the Item name
  5. Click OK

Note: The “\Views\_ViewStart.cshtml” file defines the common or default layout that all the application’s views will use. It is however possible to set a different layout by setting the Layout property, or setting it to null to not use a layout at all.

Add the Index View

  1. Expand the Angular.World > Views project
  2. Right-click Home
  3. Click Add > MVC 5 View Page with Layout (Razor)
  4. Enter Index for the Item name
  5. Click OK
  6. Double-click Index.cshtml
  7. Copy and paste the following code:

  1. Click Save and close

Install Microsoft.AspNet.Web.Optimization using NuGet

https://docs.microsoft.com/en-us/aspnet/mvc/overview/performance/bundling-and-minification

  1. Select Angular.World and right-click
  2. Click Manage NuGet Packages… or Alt+Enter
  3. Click on Browse
  4. Enter AspNet.Web.Optimization in the Search box
  5. Select AspNet.Web.Optimization
  6. Click Install
  7. Click OK in Preview dialogue box
  8. Click I Accept in License Accept dialogue box

Tip: You can monitor the installation process using Visual Studio’s Output window

Update Web.config Files

Now that the project references System.Web.Optimization, we need to update the two Web.config file.

Root Web.config

  1. Locate the config file located at the root of Hello.Angular.World project
  2. Open the config file
  3. Locate the configuration/runtime/assemblyBinding section
  4. Add the following code


Note: …/runtime/assemblyBinding represents the path to a specific XML node…

Views Web.config

  1. Locate the config file located within the Views folder
  2. Open the config file
  3. Locate the configuration/system.web.webPages.razor/pages/namespaces section
  4. Add the following code


Note: …/pages/namespaces represents the path to a specific XML node…

_Layout.cshtml Review Code

  1. Locate Views > Shared > _Layout.cshtml
  2. Double-click cshtml to open
  3. Locate the @Styles tag
  4. The @Styles tag should no longer have a red underliner

Add the BundleConfig Class

  1. Within the Angular.World project
  2. Right-click App_Start
  3. Click Add > Class…
  4. Select Class
  5. Enter cs
  6. Click Add
  7. Open cs
  8. Replace the existing code with the following:

  1. Save and close

Update the Global.asax

At this point we have written the code required to implement Bundling, however the web application doesn’t know about it, so let’s register it.

  1. Within the Angular.World project
  2. Double-click asax to open
  3. Locate the Application_Start() method
  4. Add the following code

One final thing: systemjs.config.js

Remember the “ASP.NET MVC: prefix / to specify the root” comment and that I said we would revisit systemjs.config.js file?

  1. In the root of Angular.World project
  2. Double-click config.js to open
  3. Locate ‘npm:’: ‘node_modules/’ and change to: ‘npm:’: ‘/node_modules/’
  4. Locate app: ‘app’, and change to: app: ‘/app’,
  5. Save and close

TO-DO: I’m sure with a little effort we could write a Routing module to take care of this dynamically…

Test the Hello Angular World app

  1. Select Angular.World and right-click
  2. Click Properties or Alt+Enter
  3. Click on Web
  4. Set the Start Action to Current Page
  5. Press Ctrl+S
  6. Click Debug > Start Debugging or press F5 key

Visual Studio should build your project and open the default view in a Web Browser in debug mode. It is normal for IIS to take some time to load the web application, the first time it is run (i.e. either after an IIS reset, Web config change or an application build) …

We are sending a request to http://localhost:12345 which should load the default MVC View which in turn should load the Hello Angular World app:

MVC Page Local IIS (Route 1)

Next try sending a request to http://localhost:12345/Home which should also load the default MVC View which in turn should load the Hello Angular World app:

MVC Page Local IIS (Route 2)

And finally try sending a request to http://localhost:12345/Home/Index which should also load the default MVC View which in turn should load the Hello Angular World app:

MVC Page Local IIS (Route 3)

Pages: 1, 2, 3, 4, 5, 6, 7

Hello Angular World (page 5 of 7)

Hello Angular World (from Visual Studio and Local IIS)

Pages: 1, 2, 3, 4, 5, 6, 7

Hosting with Local IIS

My preference it to develop web applications using my Local IIS server opposed to the IIS Express server that ships with Visual Studio. I have several reasons for this, two of which are:

  • You have more control over how your application is served, for instance domain names and port numbers
  • You can test your web applications even if Visual Studio is not running

Hosting node.js applications in IIS on Windows

  1. Prerequisites
  2. Install “iisnode”
    • Download iisnode from tjanczuk/iisnode GitHub
    • https://github.com/tjanczuk/iisnode
    • Once installed, navigate to: C:\Program Files\iisnode (for x64 version)
    • Open a Command Prompt window using Run as Administrator
    • Optional: To set up the sample node app:
      1. Right-click setupsamples.bat and click Run as Administrator
      2. Follow the instructions if required…
      3. Once installed open a browser and navigate to: http://localhost/node
  1. Restart IIS
    • Open a Command Prompt window using Run as Administrator
    • Type iisreset /noforce and press Enter
C:\Windows\system32>iisreset /noforce

Attempting stop...
Internet services successfully stopped
Attempting start...
Internet services successfully restarted

C:\Windows\system32>

Add an IIS Application (Website)

You will need to have already turned on Internet Information Services as a Windows Feature.

  1. Open Internet Information Services (IIS)
  2. Expend your local server node
  3. Right-click on the Sites folder
  4. Click Add Website…
  5. Enter the following:
    • Site name: Angular.World
    • Physical path: (navigate to the Hello.Angular.World project folder)
    • Port: 12345
  6. Click OK

Config Visual Studio Web Application

  1. Select Angular.World and right-click
  2. Click Properties or Alt+Enter
  3. Click on Web
  4. Change the Servers type to Local IIS
  5. Change the Project Url, for example: http://localhost:12345
  6. Press Ctrl+S

Restore “package.json”

  1. Open/expand the Angular.World
  2. Right-click json
  3. Click Restore Packages

Note: You can use Visual Studio’s Output window to monitor the progress of the packages being restored.

Test Your Local IIS Application

  1. Open your favourite browser (e.g. Chrome)
  2. Enter the full path to the _index.hml page, for example: http://localhost:12345/_index.html

HTML Page Local IIS

Note: If the Application fails, then open the Developer tools (for Chrome press F12) and review the output in the Console window

Pages: 1, 2, 3, 4, 5, 6, 7

Hello Angular World (page 4 of 7)

Hello Angular World (from Visual Studio and Local IIS)

Pages: 1, 2, 3, 4, 5, 6, 7

Hello Angular World from a HTML page

Now that the basic configuration is complete let’s create the Hello Angular World app. The table below lists the folders and files that we will add next.

Name Type Used
assets Folder Images etc. used by the Angular application
shared Folder Components shared across the Angular application
app.component.css file The main CSS file for the Angular application
app.component.ts File The main display template for the Angular application
app.module.ts File Imports the components and modules used by the Angular application
main.ts File The Angular application’s entry point

Add Folders & Files

  1. Expand the Hello.Angular.World project and right-click on app
  2. Click Add > New Folder for the following:
    • Assets
    • shared
  3. Click Add > StyleSheet for the following:
    • app.component.css

Note: When a file name includes an extra full-stop, then you need to include the file extension as part of the name.

  1. Click Add > TypeScript File for the following:
    • app.component.ts
    • app.module.ts
    • main.ts

Note: If you see the following alert, click No

Search for TypeScript Typings? [Yes|No]

Add Code to the App Files

  1. Open app.component.css and add the following code:

  1. Open app.component.ts and add the following code:

  1. Open app.module.ts and add the following code:

  1. Open main.ts and add the following code:

Update Test HTML File

  1. Expand the Hello.Angular.World project
  2. Double on the _index.html file to edit
  3. Locate the following line of code:
    //System.import(‘app’).catch(function(err){ console.error(err); });
  4. Uncomment the code by removing the prefixed //

Test the Hello Angular World app

  1. Select Angular.World project and right-click
  2. Click Set as Start Up Project
  3. Select _index.html file and right-click
  4. Click Set as Start Up Page
  5. Click Debug > Start Debugging or press F5 key

Visual Studio should build your project and open the selected Web Browser. The _index.html may take time to load the first time and should look something like this:

HTML Page IIS Express

Note: In my IIS Express example the URL is http://localhost:15426/_index.html, however your website maybe hosted on a different port number.

Pages: 1, 2, 3, 4, 5, 6, 7

Hello Angular World (page 3 of 7)

Hello Angular World (from Visual Studio and Local IIS)

Pages: 1, 2, 3, 4, 5, 6, 7

Angular Folder & File Structure

Now to add the basic folder and files structure required to build a simple Angular App. My intentions are to remain true to the conventions set out by Angular while remaining sympathetic to ASP.NET MVC. The items in grey were included automatically during the projects creation, the items in black we have already added and the items in red we are about to add.

Name Type Used Origin Added
app Folder Container for the Angular App files Angular Manually
App_Data Folder Included during the project creation ASP.NET MVC VS Template
App_Start Folder Included during the project creation ASP.NET MVC VS Template
Content Folder CSS files and related image files ASP.NET MVC Manually
=> site.css File Add to the Content folder General Manually
Controllers Folder Included during the project creation ASP.NET MVC VS Template
Images Folder Included during the project creation ASP.NET MVC VS Template
Models Folder Included during the project creation ASP.NET MVC VS Template
Scripts Folder JavaScript files General Manually
Views Folder Included during the project creation ASP.NET MVC VS Template
_index.html File HTML test page for Angular General Manually
Favicon.ico File Favourite or shortcut icon/images General VS Template
Global.asax File ASP.NET application file ASP.NET MVC VS Template
package.json File NPM package configuration Quick Package Installer NPM
Packages.config File NuGet package configuration file ASP.NET MVC VS Template
systemjs.config.js File Angular App configuration file Angular Manually
tsconfig.json File TypeScript configuration file TypeScript Manually
Web.config File Web application configuration file ASP.NET MVC VS Template

 Added Default Folders

  1. Select Hello.Angular.World and right-click
  2. Click Add > New Folder
  3. Give or rename the folder to match one of the following and repeat until the list is complete:
    • app
    • Content
    • Images
    • Scripts

Added “systemjs.config.js” Files

The information below is based directly upon the Angular 2 QuickStart / systemjs.config.js file
https://github.com/angular/quickstart/blob/master/systemjs.config.js

  1. Select Angular.World and right-click
  2. Click Add > JavaScript File
  3. Set the Item name: systemjs.config.js
  4. Click OK

The JavaScript code will look like this:

You may notice two comments containing “ASP.NET MVC: prefix / to specify the root”. This is to remind us to add the “/” prefix when we start working with MVC files.

Added Test HTML File

In readiness to test our Hello Angular World app, lets add an HTML file.

  1. Select Hello.Angular.World and right-click
  2. Click Add > HTML Page
  3. Set the Item name: _index.html
  4. Click OK

The default HTML code will look like this:

Update the code so that it looks like this:

Notice that the “System.import(‘app’).catch(function(err){ console.error(err); });” has been commented out, we will return to this section of code later.

Add Site.css file

Before I forget, let’s add a style sheet called Sites.css

  1. Within the Hello.Angular.World project, right-click Content
  2. Click Add > Style Sheet
  3. Set the item name css
  4. Click OK
  5. Copy and paste the following code:

  1. Click Save and close

Pages: 1, 2, 3, 4, 5, 6, 7

Hello Angular World (page 2 of 7)

Hello Angular World (from Visual Studio and Local IIS)

Pages: 1, 2, 3, 4, 5, 6, 7

NPM Packages

Now that we have a basic ASP.NET MVC 5 project let’s install some NPM Packages. Once you have installed the first NPM Package you will see a new file, called package.json, added to your Project’s root. We will look at the package.json in more details later.

Install TypeScript 2 Package

To give you an idea of how to install NPM Package, let’s use the TypeScript 2 NPM Package as an example you can follow for all the other packages.

http://www.typescriptlang.org/

  1. Select Hello.Angular.World and right-click
  2. Click Quick Install Package
    Visual Studio project menu showing the Quick Install Package option
  3. Select npm, enter typescript and select latest version (in this case 2.1.4)
    NPM browser with typescript 2.1.4 selected
  4. Click Install

Tip: You can monitor the installation process using Visual Studio’s Output window

Note: TypeScript is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to clean, readable, standards-based JavaScript. Try it out at http://www.typescriptlang.org/playground.

Edit the ‘package.json’ File

Now that you have installed a NPM Package locate the package.json file at the root of the Hello.Angular.World project.

  1. Open the package.json file in Visual Studio (text editor) and review the content
    Basic package.jason file
  2. Change the value for “name“, from “myproject” to “hello-angular-world
  3. Add “description”: “Hello Angular World (from Visual Studio and Local IIS) is a start-up project in which two worlds collide… “
  4. Add “license”: “MIT”
  5. Add “repository”: {} or add your Git details…
  6. Add “scripts”: {} and leave it empty for now
  7. Add “dependencies”: {} and leave it empty for now
  8. Move “devDependencies” : { “typescript”: “^2.1.4” } to the end (this is just a personal preference not requirement)
  9. Click File > Save or Ctrl+S

Note: Specifics of npm’s package.json handling https://docs.npmjs.com/files/package.json

Before we continue with the process of adding PMN Packages I would like to point out that the Quick Install Package tool seems to always add the package reference to the devDependencies section. I am assuming this is in order to avoid adding unnecessary packages to test harnesses or transpilers the production app. You can read more here: https://docs.npmjs.com/files/package.json

Add “dependencies” Packages

The following packages should be added to the dependencies section, however as I mentioned earlier they are added to the devDependencies section and so we need to manually update the package.json file once we have finished importing the list.

  1. Select Hello.Angular.World and right-click
  2. Click Quick Install Package
  3. Select npm, enter the values in the table below
  4. Click Install
Package Name Latest Version* NPM Website Notes
@angular/common Latest version
@angular/compiler Latest version
@angular/core Latest version
@angular/forms Latest version
@angular/http Latest version
@angular/platform-browser Latest version
@angular/platform-browser-dynamic Latest version
@angular/router Latest version
@angular/upgrade Latest version
angular2-in-memory-web-api Latest version (0.0.21) https://www.npmjs.com/package/angular2-in-memory-web-api Replaced with angular-in-memory-web-api
angular-in-memory-web-api 0.2.4 https://www.npmjs.com/package/angular-in-memory-web-api/tutorial UNMET PEER DEPENDENCY

    • rxjs@5.0.1
    • zone.js@0.7.4 extraneous
bootstrap 3.3.7 https://www.npmjs.com/package/bootstrap
core-js 2.4.1 https://www.npmjs.com/package/core-js
es6-module-loader 0.17.10 https://www.npmjs.com/package/es6-module-loader GET http://localhost:6854/node_modules/es6-module-loader/dist/es6-module-loader.js 404 (Not Found)
jquery 3.1.1 https://www.npmjs.com/package/jquery
reflect-metadata 0.1.9 https://www.npmjs.com/package/reflect-metadata
rxjs 5.0.2 https://www.npmjs.com/package/rxjs
systemjs 0.19.41 https://www.npmjs.com/package/systemjs To avoid errors don’t get an old version
zone.js 0.7.4 https://www.npmjs.com/package/zone.js

*At the time of writing…

Warning: The Quick Install Package’s Latest Version drop-down-list is not sorted numerically (the data is as string value and not number).

Tip: You can monitor the installation process using Visual Studio’s Output window

  1. Open the package.json file in Visual Studio (text editor)
  2. Move the above packaged to the dependencies section
  3. Save and close the file

Add “devDependencies” Packages

These packages should be added to the “devDependencies” section of the package.json file.

  1. Select Angular.World and right-click
  2. Click Quick Install Package
  3. Select npm, enter the values in the table below
  4. Click Install
Package Name Latest Version* NPM Website
@types/core-js Latest version https://www.npmjs.com/package/@types/core-js
@types/node Latest version https://www.npmjs.com/package/@types/node
concurrently 3.1.0 https://www.npmjs.com/package/concurrently
lite-server 2.2.2 https://www.npmjs.com/package/lite-server
tslint 4.20 https://www.npmjs.com/package/tslint
typescript 2.1.4 https://www.npmjs.com/package/typescript
typings 2.1.0 https://www.npmjs.com/package/typings

*At the time of writing…

Warning: The Quick Install Package’s Latest Version drop-down-list is not sorted numerically (the data is as string values and not number).

Tip: You can monitor the installation process using Visual Studio’s Output window

  1. Open the package.json file in Visual Studio (text editor)
  2. Review the contents, however there shouldn’t be any further actions to complete
  3. Close the file

Restore NPM Packages

Just as we sometime need to restoring NuGet packages, we also need to restore NPM packages too.

  1. Navigate to root of the Angular.World project
  2. Right-click package.json
  3. Click Restore Packages

Tip: You can monitor the installation process using Visual Studio’s Output window

Visual Studio project with node_modules

Once the restoration process is complete, then the Hello.Angular.World project should contain a hidden folder called node_modules, see the image above for details.

Update the “scripts” Property (package.json)

This section can contain a list of script commands that automate life cycle processes for your package. For more information: https://docs.npmjs.com/misc/scripts

  1. Navigate to the root of the Angular.World project
  2. Open the package.json file in Visual Studio (text editor)
  3. Add the following properties/commands:
  4. Save and close the file

‘tsconfig.json’ file

Now that we have our NPM packaged loaded, lets configure the TypeScript configuration file. The tsconfig.json file instructs the compiler on how to generate JavaScript files.

I’ve based the information below directly on the Angular website’s TypeScript Configuration article: https://angular.io/docs/ts/latest/guide/typescript-configuration.html

  1. Select Hello.Angular.World and right-click
  2. Click Add > JavaScript File
  3. Set the Item name to: tsconfig.json
  4. Click OK
  5. Add the following code:
  6. Save and close

Note: I have included “removeComments”: false for debugging purposes…

Pages: 1, 2, 3, 4, 5, 6, 7

Hello Angular World (page 1 of 7)

Hello Angular World (from Visual Studio and Local IIS)

I have written this article and the accompanying Visual Studio 2015 project as an exploration of how Angular 2 and ASP.NET MVC 5 can coexist and I have tried to remain true to both frameworks, respecting naming conventions and file structure. While carrying out research for this article, I came across the Angular2Mvc5Application Project Template which did tick most of the boxes, however I wanted to know more about the inner workings, structure and naming conventions.

As you will see I have covered a lot of detail, so you may decide to download the source code to dip in and out as you need, or to read the article from end to end. Either way, the complete source code and project files can be found on GitHub: https://github.com/sionjlewis/Hello.Angular.World

The following topics are covered:

Note: You may notice references to My.iTunes within the code, this is because I extracted this code from another solution with the sole purpose of keeping the example as simple as possible.

Prerequisites

Before we begin, please make sure that you have ticked off the following prerequisites. The following list builds upon the Visual Studio 2015 Quickstart article published on the Angular website: https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html#!#prereq1

  1. Turn on the Internet Information Services Windows Feature.
    This action is only required if you plan to develop against your Local IIS server, opposed to IIS Express which ships with Visual Studio.
  2. Download and install Node.js (and NPM) https://nodejs.org/en/download/
  3. Confirm that you have Visual Studio 2015 Update 3 installed:
  4. Configure Visual Studio to use the global external web tools, and not the tools that ship with Visual Studio:
    • Open Visual Studio 2015 and click: Tools > Options
    • Navigate to: select Projects and Solutions > External Web Tools
    • Add the nodejs Program Files directory at the top of the Locations of external tools list. In my case this path is C:\Program Files\nodejs
      Visual Studio: locations/paths to External Web Tools
      Note: Visual Studio will now look first for external tools in the current workspace, if not found it will then look in the global path and if it is not found there, Visual Studio will use its own versions of the tools.
      From:
      https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html#!#prereq1
  1. Install TypeScript 2 for Visual Studio 2015:

Note: TypeScript 2.0 is now available for Visual Studio https://blogs.msdn.microsoft.com/typescript/2016/09/22/announcing-typescript-2-0/

  1. Set Visual Studio 2015 to Run as Administrator
    • Locate the short cut or favourite that you use to open Visual Studio
    • Right-click and click Properties
    • Click Shortcut > Advanced…
    • Tick the Run as administer checkbox
    • Click OK

Note: You may run into difficulties debugging without Run as administer, however depending on your UAC settings you are likely to see a User Access Control promote every time you open Visual Studio. Click Yes to continue to open Visual Studio.

  1. Restart Visual Studio

Note: It is probably a good idea to restart your machine after the next section

NPM Task Runner & Package Installer

Install the following Visual Studio Extensions (if not already installed):

  1. NPM Task Runner
    https://marketplace.visualstudio.com/items?itemName=MadsKristensen.NPMTaskRunner
  2. Package Installer
    https://marketplace.visualstudio.com/items?itemName=MadsKristensen.PackageInstaller
  3. Restart your machine

Note: I couldn’t find the Task Runner Explorer window at first, however after restarting my machine and some mucking around I found here: View > Other Windows > Task Runner Explorer (Ctrl+Alt+Bkspace)

Create a Visual Studio Project

At this point I am assuming you have completed the prerequisites and have Visual Studio 2015 open and ready to create a new project (and solution).

  1. Select: File > Add > New Project…
  2. Select: Visual C# > Web > ASP.NET Web Application (.NET Framework)

Note: At the time of writing this I had .NET Framework 4.6.1 installed

  1. Enter:
    • Name: Hello.Angular.World
    • Location: <select location>
    • Solution name: Hello.Angular.World
    • Tick Create directory for solution
  2. Click OK
  3. Select a template Empty and tick MVC
    ASP.NET 4.6.1 Template options
  4. Click OK

Your project should look something like this:
Basic ASP.NET MVC 5 project structure

Pages: 1, 2, 3, 4, 5, 6, 7

Angular 2: Quick Start Notes Part #1

These are my notes, made while watching Deborah Kurta’s Angular2: Getting Started course, hosted by Pluralsight. Most, if not all, of this information can be found within Deborah’s course, however by stripping this information out I hope to jog memories…

Tools & Setup: Macintosh (OS X)

How to use Visual Studio Code with GitHub:

Download and install:
1. Visual Source Code: https://code.visualstudio.com
2. Git: https://git-scm.com/download

Clone a Git:
1. Open a Terminal window and change the directory to the location you would like to save the folders and files, for example:

Mac:~ sion$ cd Documents/GitHub/
 Mac:GitHub sion$

2. Enter the following command:

Mac:GitHub sion$ git clone https://github.com/DeborahK/Angular2-GettingStarted.git

Once complete, open the folder with Visual Studio Code.

Commit changes:

  • From Visual Studio Code select Push
  • If VS Code does not prompt for login and password, open the Terminal in the context of the code:
    a. Select Explorer
    b. Right click on a file in the root of the folder and click Open in Terminal
    c. Enter the following command:

    Mac:GitHub sion$ git push

    d. Enter the Username and Password for your GitHub account
    e. Wait for the command to complete before restarting VS Code
    f. VS Code should now be able to Push without errors
    g. Optional: install a credential helper https://help.github.com/articles/caching-your-github-password-in-git/

More Information

https://code.visualstudio.com/docs/editor/versioncontrol
https://help.github.com/articles/caching-your-github-password-in-git/

Please see second post in this series for install and configure of the NPM (Node Package Manager) command line utility

Jasmine with Visual Studio and SharePoint Apps – Part 3

Jasmine Fixtures and Chutzpah Test Adaptors

In my last post I described how to configuring an “App for SharePoint” VMC project to use Jasmine and Jasmine-Jquery for BDD with Visual Studio using Chutzpah Test Adaptor or a Web Browser. In this post I want to talk about Fixtures and a major pitfall I’ve found when working with Chutzpah Test Adaptor for the Test Explorer.

How to Install Chutzpah Test Adaptor

1. Install VS Extensions
Open Visual Studio 2013 > TOOLS > Extensions and Updates…

Within the Left panel, click on Online and search for Chutzpah Test

Download:

And then restart Visual Studio

2. Configure Test Explorer

Open Visual Studio 2013 > TEST > Windows > Test Explorer and pin the window to suite your preference…

Top left of the Test Explorer window, click on the button “Run Test After BuildRun Test After Build

Why Chutzpah Test Adaptor?

Chutzpah Test Adaptor for the Test Explorer is an extremely popular open source extension for Visual Studio that enable developers to run Jasmine and other test frameworks directly within Visual Studio Test Explorer.

Side note: Chutzpah Test Adaptor uses the PhantomJS headless browser to run your tests.

This is incredibly useful for developer as we can quickly configure VS Test Explorer to display the results of changes made to either Spec or Source upon saving. And the process up to the point we want to introduce Fixtures to our Specs is greater, however that is where the problems start…

What are Fixtures?

A set of functions included with Jasmine-JQuery that enables developers to injecting “fixtures” into the DOM to be cleaned up after each spec. Fixtures can be HTML, CSS or JSON and either written inline or loaded up from an external file.

When Would Load a File as a Fixture?

If for example you need to write a Spec that described a User accessing his/her colleague’s User Profile Page, it may not be possible to guaranty available or stable of the test data in a development environment. In which case we would generate a JSON file and save it to the Fixtures folder (see Part 2) and load the data up before each “IT” case was run.

What’s The Problem?

When you test you Spec using the SpecRunner View/Page within a Web Browser Fixtures work fine and all the test pass or fail as expected. However when you attempt to run the same spec within Visual Studio using Chutzpah Test Adaptor the same test that passed now fail.

The reason for this because Chutzpah generates a HTML file on the fly and temporally saves it to the file system and therefore does not have HTTP or HTTPS address and as a consequence Jasmine-JQuery is unable to resolve a URL throwing an error.

Log Message: Error: Fixture could not be loaded: ../Scripts/jasmine/fixtures/filename.html (status: error, message: undefined) from c:\…\sjlewis.sharepoint.jasmine2web\scripts\jasmine\specs\fixtures_spec.js

Having done a little more digging it would appear the jasmine.Fixtures.prototype. getFixtureHtml_() function requires a URL which is either resolved as NULL or not being passed.

Side note: The "spcontext.js" script throws an error because window.location.href is null

The Workarounds

As there two possible three options that we may use to get around this limitation, however with option you choose will depending on the size of the data or DOM structure that you are wanting to testing your Specs against.

1.       Load data into the DOM using for example the setFixtures() function.

setFixtures('<div class="sandbox">hello there</div>');

This work fine in both in Visual Studio and a Web Browser. However writing large amounts of HTML structure in JavaScript is not ideal as it is time consuming and error prone.

2.       Attempt to load the file into the DOM using the loadFixtures() function but wrap the code in a try-catch block. I’ve highlighted the code of interest in red:

describe("Fixtures: Learning about", function () {
    beforeEach(function () {
        // You can configure this path to fixtures...
        jasmine.getFixtures().fixturesPath = '../Scripts/jasmine/fixtures';
    });

    it("offers three crucial functions", function () {
        expect(readFixtures).toBeDefined();
        expect(setFixtures).toBeDefined();
        expect(loadFixtures).toBeDefined();
    });

    // Fails to run within "Chutzpah Test Adaptor for the Test Explorer".
    it("can load fixtures from a file", function () {
        try {
            loadFixtures('filename.html');
            expect($('#jasmine-fixtures')).toExist();
        } catch (ex) {
            console.log("#### ERROR: [" + ex + "]");
        }
    });

    // Fails to run within "Chutzpah Test Adaptor for the Test Explorer".
    it("can read fixtures without appending to DOM", function () {
        try {
            var fixture = readFixtures('filename.html');
            expect(fixture).toContain('p');
            expect($(fixture).find('p')).toHaveText('Hello World');
        } catch (ex) {
            console.log("#### ERROR: [" + ex + "]");
        }
    });​

    it("can also receive the fixture as a parameter", function () {
        setFixtures('<div class="sandbox">hello there</div>');
        expect($('.sandbox')).toExist();
    });

    it("offers a sandbox function for convenience", function () {
        expect(sandbox).toBeDefined();
        setFixtures(sandbox({ 'class': 'some-class' }));
        expect($('.some-class')).toExist();
        expect($('#sandbox')).toHaveClass('some-class');
    });
});​

So none of the Specs calling the loadFixtures() function will fail anymore when tested within Visual Studio, however  just like a false negative the false positive would not be tested for within the a Web Browser.

3.       Look at using jasmine-fixture, apparently this helper library may reduce the about of HTML required to write when creating a DOM structure inline, however it may not be of any use for writing JSON..?

jasmine-fixture

https://github.com/searls/jasmine-fixture

Conclusion

So when dealing with large amounts of data or complicated DOM structure option2 may be the best bet however we will need to decide on how to deal with false positive or negatives… As for small amount of data then option3 may prove to be better than option1 however further investigation is required.

Looking longer term, this area of development is becoming more and more popular as development teams continue on their quest to reduce bugs I’m sure solutions will be found.

Jasmine with Visual Studio and  SharePoint Apps​ – Part: 123

Useful Links​

Jasmine 2.0 Documentations
http://jasmine.github.io/2.0/introduction.html

Jasmine.JS Download
https://github.com/pivotal/jasmine

Jasmine-JQuery.JS Download
https://github.com/velesin/jasmine-jquery

Chutzpah JavaScript Test Runner
https://chutzpah.codeplex.com

Chutzpah Test Adapter for the Test Explorer
http://visualstudiogallery.msdn.microsoft.com/f8741f04-bae4-4900-81c7-7c9bfb9ed1fe

Chutzpah Test Runner Context Menu Extension
http://visualstudiogallery.msdn.microsoft.com/71a4e9bd-f660-448f-bd92-f5a65d39b7f0

jasmine-fixture
https://github.com/searls/jasmine-fixture

Uninstall Jasmine (NuGet Package)

Jasmine with Visual Studio and SharePoint Apps – Part 2

How to Structure a MVC Project (without NuGet)

Last week I wrote about how to configure Jasmine to run within Visual Studio using Chutzpah Test Adaptors. However since then I’ve run into a number of issues for which I will share my thoughts in this post.

The first of these is in regards to implementing Jasmine using NuGet. In the main I’m a big fan of NuGet, however when it comes lesser known frameworks such as Jasmine and Jasmin-JQuery the packages are either not available or most up to date. With that in mind I’ve decided to manage the Jasmin and Jasmin-Jquery manually using the steps described below.

Configuring an App for SharePoint Project

Step 1: Install Chutzpah

Skip this section if you have previously installed the Chutzpah Test Adaptor for the Test Explorer extension, as this action only needs to be carried out once per development environment.

As described in my previous post; install the Chutzpah Test Adaptors by opening Visual Studio 2013 > TOOLS > Extensions and Updates… Within the left panel, click on Online and search for Chutzpah Test and click “Download” for the following extension:

  • Chutzpah Test Adaptor for the Test Explorer
  • Chutzpah Test Runner Context Menu Extension

Once installed restart Visual Studio.

Step 2: Uninstall Jasmine (NuGet Package)

Uninstall Jasmine (NuGet Package)For existing projects only; removal of either the SharePoint Jasmine Test Runner or Jasmine Test Framework NuGet packages.

Open Visual Studio 2013 > TOOLS > NuGet Package Manager > Manage NuGet Packages for Solution… Within the left panel, click on installed packages and navigate to the package to remove (e.g. SharePoint Jasmine Test Runner) and click Manage.

A modal window will open; deselect the project(s) you would like to remove the package from and click OK.

Note: the NuGet Package may leave files and folders behind, which you will need to clean up manually.

Step 3: Add Jasmine & Jasmine-JQuery

To add Jasmine to a new or existing Visual Studio project, start by downloading the following libraries:

Note: in both cases I chose to download the “master” branch.

Jasmine

Solution Explorer

  1. Right click on the ZIP file and “Extract All…
  2. Navigate to the “dist” directory and extract the latest ZIP file, in my case this is: jasmine-standalone-2.0.3.zip.
  3. Open extracted folder and navigate to the “lib\ jasmine-2.0.3” directory.
  4. From the root of the VS Project, navigate to the “Scripts” folder and add a sub-folder “jasmine“.
  5. Copy the following files from “lib\ jasmine-2.0.3” to “Scripts\jasmine” folder:
    • boot.js
    • console.js
    • jasmine-html.js
    • jasmine.js
  6. Back to the root of the VS Project, navigate to the “Content” folder and add a sub-folder called “jasmine“.
  7. Copy the following files from “lib\ jasmine-2.0.3” to “Content\jasmine“:
    • ​​Jasmine.css
    • Jasmine_favicon.png

The structure of your VS project should now look similar the image on the right.

Jasmine-Jquery

  1. From the root of the VS project, navigate to “Scripts\jasmine” and add a sub-folder called “helpers
  2. Extract the jasmine-jquery-master.zip file
  3. Copy the jasmine-jquery.js file from the “lib” folder to the “Scripts\jasmine\helpers” folder.

At this point you have the relevant tools write and test Jasmine Specs from within Visual Studio and running the test(s) using the Chutzpah Test Adaptor for the Test Explorer extension. However due to some limitations which I will go into detail later, I would recommend adding Spec Runner page.

Step 4: Added a SpecRunner View

Navigate back the jasmine-standalone-X.X.X folder you will see a file called SpecRunner.html. In this section I will describe how to recreate this file within your MVC project.

  1. Add a new “MVC5 Controller – Empty” file to your project called “JasmineContoller
  2. Within the “Views” folder add a new sub-folder called “Jasmine”
  3. Add a “MVC 5 View Page (Razor)” called “SpecRunner”
  4. Open JasmineContoller.cs and
    • Optionally add “using Microsoft.SharePoint.Client;” at top of the file.
    • Rename “public ActionResult Index()” to be “public ActionResult SpecRunner()
  5. Open the SpecRunner.cshtml file and add the following reference in between HEAD tag:

Note: we will add our references to our Specs and Source files below the comments later on.

Step 4 Folder Structure

I’m sure you would agree when it comes to managing files a consistent structure is key. So we are going to add another 3 more folders to our project:

  1. Fixtures               to be added under Scripts/jasmine
    this folder will contain any fixture file you have created for your specs.
  2. Specs                 to be added under Scripts/jasmine
    the folder will contain all your specs files.
  3. Src                      ​to be added directly under Scripts
    this folder will contain all your custom JavaScript file for project.

So now the MVC (App for SharePoint) project should have a structure something like this:

MVC App for SharePoint Project​
        • Controllers​​
              • ​​JasmineController.cs
        • Scripts
              • Jasmine
                    • fixtures ​​
                          • helloWorld_fxtr.js
                    • helpers
                          • jasmine-jquery.js
                    • specs
                          • helloWorld_spec.js
                          • boot.js console.js
                          • jasmine-html.js
                          • jasmine.js
                    • Src
                          • helloWorld.js
                          • _jasmine_ref.js_references.js
                          • Jquery-X.XX.X.js
    • Views
            • Jasmine
                  • ​​​​​SpecRunner.cshtml

Getting Ready To Run Tests from Visual Studio

Before we attempt to run any tests you may remember from my previous post that we need to manage the references stored within the _reference.js file.

REMEMBER: to avoid Chutzpah running your tests more than once, you need to remove references to your Spec files from the _reference.js file (every time you add a new JS file).

We also need to add one or more references to the top of each Spec files to tell Visual Studio & Chutzpah which Source Scripts are to be referenced by a spec. For example the helloWorld_spec.js file need the following to reference to be able to run:

/// <reference path="src/helloWorld.js" />

As your Specs reference more and more source scripts and libraries, the spec files run the risk of become chocked up with references. To avoid that adding a reference to a file such as _reference.js file would work except it has one undesirable side effect. When referencing the _reference.js file directly from a Spec files I noticed the following error displayed at least twice:

Error: TypeError: ‘null’ is not an object (evaluating ‘getAuthorityFromUrl(window.location.href).toUpperCase’)

Which in turn cause a number of other false errors…

With that in mind taking a copy of the _reference.js file and renaming it to _jasmine-ref.js file and removing the following:

  • /// <autosync enabled=”true” />
    this is irrelevant within out custom file.
  • /// <reference path=”spcontext.js” />
    this is causing the multiple errors.

This is what my _jasmine-ref.js file looks like:

/// <reference path="modernizr-2.6.2.js" />
/// <reference path="jquery-1.10.2.js" />
/// <reference path="bootstrap.js" />​​

/// <reference path="respond.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

/// <reference path="knockout-3.2.0.js" />
/// <reference path="jasmine/boot.js" />
/// <reference path="jasmine/console.js" />
/// <reference path="jasmine/jasmine-html.js" />
/// <reference path="jasmine/jasmine.js" />
/// <reference path="jasmine/helpers/jasmine-jquery.js" />

/// <reference path="src/helloworld.js" />

Next then add the following reference at the top of each of your Spec files:

/// <reference path="../../_jasmine_ref.js" />​

Note: This workaround will not remove the error completely, but will reduce it to a single output.

Testing a Hello World Spec

When writing new code you need to get into the habit of writing a Spec first and then Source code to pass the test. So in this sections let write a simple Hello World Spec and Code:

  • Add a new JS file to the specs folder called helloWorld_spec.js
    (see folder structure above for details)
  • Open the helloWorld_spec.js and add the following code:
1.  /// <reference path="../../_jasmine_ref.js" />
2.
3.  describe("HelloWorld", function () {
4.    it("will return true", function () {​
5.             var result = firstTest();
6.             expect(result).toBe(true);
7.    });
8.  });
  • Open Test Explorer (TEST > WINDOWS > Test Explorer) and click on Run All and your test should fail. This is because you we have not written any code yet…
  • Add a new JS file to the src folder called helloWorld.js
  • Open the helloWorld.js and add the following code:
1.  "use strict";
2.
3.  var firstTest = function () {
4.    return true;
5.  }
  • Open Test Explorer and click on Run All and your test should now pass.

Congratulations you have just written a Spec and tested it within Visual Studio.

Getting Ready To Run Tests from a Web Browser

Fortunately the workarounds mentioned above are not required when running Jasmine Specs in a Web Browser. So remember back to the step “Added a SpecRunner View”, well we need to first add a reference each to your Spec and Source files, see my HelloWorld example code below:

​@{
Layout = null;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jasmine Spec Runner</title>

<meta name="description" content="Dispalays test results based upon from Jasmin specifciations" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<link rel="shortcut icon" type="image/png" href="/Content/jasmine/jasmine_favicon.png">

@Styles.Render("~/Content/jasmine/jasmine.css")
@Scripts.Render("~/Scripts/jasmine/jasmine.js")
@Scripts.Render("~/Scripts/jasmine/jasmine-html.js")
@Scripts.Render("~/Scripts/jasmine/boot.js")
@Scripts.Render("~/Scripts/jquery-1.10.2.js")
@Scripts.Render("~/Scripts/knockout-3.2.0.debug.js")
@Scripts.Render("~/Scripts/jasmine/jasmine.js")
@Scripts.Render("~/Scripts/jasmine/helpers/jasmine-jquery.js")
@Scripts.Render("~/Scripts/jasmine/helpers/jasmine-jquery.js")

<!-- include spec files here... -->

@Scripts.Render("~/Scripts/jasmine/specs/helloWorld_spec.js")

<!-- include source files here... -->

@Scripts.Render("~/Scripts/src/helloWorld.js")

</head>
<body>
</body>
</html>​

Once you have done that you are ready to hit [F5] and deploy your SharePoint App and run the MVC Project from IIS Express.

TIP: If like me you get fed up having to hit [F5] every time you want to test a Specs then update your MVC project to use the Local IIS. Just make sure that you specified https and not http for the Project URL.

Conclusion

So we have covered a lot of ground in this post, from downloading the latest Jasmine library and Jasmine-JQuery helper, to structuring the library files, specs, fixtures, helpers and source files, we also covered Visual Studio references and adding a SpecRunner View for in Browser Testing and finally we wrote a hello world test.

In “Part 3” I plan to cover Fixtures and a major pitfalls when testing Chutzpah in Visual Studio.​

Jasmine with Visual Studio and  SharePoint Apps​ – Part: 123