Category Archives: Visual Studio

SPFx-People-Search

SharePoint/SPFx: Returning to Webpart Development Part #4 (with React Hooks)

Recently I was asked to develop a webpart for a modern SharePoint site. My first thoughts, where do I start; I haven’t done any webpart development for years? I would like to share my journey with you over the next few posts and hope my experience will help new and returning developers along the way.

In my previous post I covered:

In this post I will cover:

This article is different to its predecessors in the series, because I have published the SPFx-People-Search webpart solution to my GuiHub repository, I will be focusing on what I have found challenging about writing this webpart with React Hooks, SPFx and Microsoft Graph.

In the previous article I created the Project Folder Structure with stub files ready to add code. So now I can focus on creating the components such as the Service and User Interface. I deliberated on where to start, creating the Service layer or UI. Deciding to start with a service class called MSGraphService.ts and its corresponding interface.

Note: I have added a data JSON file, however I have more work to do before this can be used for testing in the local workbench.

Service Layer

The MSGraphService is based upon the Service Locator pattern which I took inspiration from an old colleague Vardhaman Deshpande who wrote this article. The MSGraphService files are located here:

Having decided on this pattern and how to implement it, the other challenges I had with the Microsoft Graph API included:

Microsoft Graph User Photo

What to do with the data returned by Microsoft Graph User Photo endpoint. With the lack of documentation, the Graph Explorer is great, but it still took a bit of work to figure out what to do with “Blob Strings” …

Microsoft Graph Explorer Me/User Photo
https://developer.microsoft.com/en-us/graph/graph-explorer?request=me%2Fphoto%2F%24value&method=GET&version=v1.0

See the getUserPhoto() function located within MSGraphService.ts

User Presence

What the different User Presence options are: User may display…? Again, the Graph Explorer was a great help, it went a long way to making up for the lack of documentation.

Microsoft Graph Explorer Me/User Presence
https://developer.microsoft.com/en-us/graph/graph-explorer?request=me%2Fpresence&method=GET&version=beta

See the getUserPresence() function located within MSGraphService.ts and the implementation within ResultCard.tsx

Configure the API permissions requests

This time I can praise the documentation by Microsoft: “To consume Microsoft Graph or any other third-party REST API, you need to explicitly declare the permission requirements from an OAuth perspective in the manifest of your solution.” For more information see https://docs.microsoft.com/en-us/sharepoint/dev/spfx/use-aad-tutorial#configure-the-api-permissions-requests

And my working example of the package-solution.json can be found here: https://github.com/sionjlewis/SPFx-People-Search/blob/main/config/package-solution.json

User Interface

To keep things simple, I kept the PeopleSearchWebPart.ts webparts “main/entry” class, created by the SPFx Yeoman scaffold, pretty much “as is”. Converting this class to React Hook seemed to be more hassle that it was worth.

Using React Hooks with the SPFx framework

So unlike all the React.JS Hook Documentation, I was unable to implement a basic function, but instead I found I needed to write something similar to the following:

export const PeopleSearch: React.FunctionComponent<IPeopleSearchProps> = (props) => { 
    … 
};

Writing the Hooks

Having organised the components into a Project Folder Structure, I started at the top:

  1. Added references and initiated object to PeopleSearchWebPart.ts and passed them on to PeopleSearch.tsx
  2. Updated the IPeopleSearchProps.tsx interface and added each of the “Wrapper” Hooks to the return statement
  3. Focusing on the ResultWrapper, I added the “useState” and “useEffect” Hooks to handle the getFilteredUsersExpanded() data, which I then “mapped” instances of the ResultCard.tsx
  4. Before focusing on details such as User Presence and User Photo, I output the “raw” User data to the user interface from the return statement. I used this technique to confirm that the service layer was connecting to and returning the data as expected

I continued on with this process of working until I “finished” the Results components and then moved onto the Footer and Search components.

You may have noticed that I have not started on the filter components as my strategy is to get something working as quickly as possible, with the following goals:

  • Enables demos and feedback loop to start earlier
  • Test the API(s) to confirm that they work as expected (or documented) and update our strategy if they don’t

Other Stuff

underscore.js vs Lodash

Back in my “JavaScript” days I was a big fan of underscore.js, so I tried it within this project, however I found the library too cumbersome to import and so I ended up replacing it with Lodash which seems to play better with TypeScript.

Conclusion

I am now a self-confessed fan of React Hooks and have really enjoyed the process of building this webpart. As with any new development technique or process, I will find better ways of doing things as I do more, but I like how clean the code looks and reckon the modularity will make the solution so much easier to support.

Siôn Lewis

28/11/2020

When attempting to debug a recently copied SPFx solution I kept seeing the following error displayed by my browser:

Cannot GET /temp/workbench.html

As per usual, I had entered the following command into the VSCode Terminal window:

gulp serve --nobrowser

Selected the Local workbench profile and clicked on Start Debugging, which attempted to opened the following URL with Google Chrome:

https://localhost:4321/temp/workbench.html

The solution to stop this “Cannot GET” error was to enter the following URL:

https://localhost:5432/workbench

This appears to reset the “service, cache or something” causing the error to go away.

Now I can debug as per normal again.

SharePoint/SPFx: Returning to Webpart Development Part #3 (with React Hooks)

Recently I was asked to develop a webpart for a modern SharePoint site. My first thoughts were; where do I start; I haven’t done any webpart development for years? I would like to share my journey with you over the next few posts and hope my experience will help new and returning developers along the way.

In my previous post I covered:

In this post I will cover:

Recommended Reading

The official React website has some fantastic documentation and to avoid duplicating what they have already published I would recommend reading the “Thinking in React” article before we move on. I found the section “Step 2: Building A Static Version In React” particularly useful to kick-off the build of this webpart.

Using React Hooks with the SPFx Framework

The first thing I did was to import the React module using following statement:

import React, { useState, useEffect } from 'react';

When I tried to build the project, I received the following error:

Module '"c:/.../SJLewis.SPFx.Webparts.People/node_modules/@types/react/index"' can only be default-imported using the 'allowSyntheticDefaultImports' flagts(1259)
index.d.ts(46, 1): This module is declared with using 'export =', and can only be used with a default import when using the  'allowSyntheticDefaultImports' flag.

Plus, the React and ReactDom import statements are underlined in red:

React and ReactDom import statement is underlined in red

What is allowSyntheticDefaultImports? It allows default imports from modules with no default export and it does not affect code emitted, it is just typechecking.

How to enable allowSyntheticDefaultImports

Open the tsconfig.json file and add the following code to the “compilerOptions” section:

"allowSyntheticDefaultImports": true

Your tsconfig.json file should look something like this:

allowSyntheticDefaultImports

And now TypeScript is happy…

React and ReactDom import statement are validated

Before moving on to the next step, let’s build the project and commit your changes to source control (just in case we break the project later).

Installing additional NPM packages

We don’t always know all of the packages we want to use upfront, however I like to add what I can upfront. For this example, I am going to add the following npm packages to my project. Enter the commands into the VS Code Terminal window:

And finish by doing some “housekeeping” and confirming that the project builds:

gulp clean
npm shrinkwrap
gulp build

Project Folder Structure

I like to start by creating a folder structure based upon the Components and Services listed within my wire-frame(s) and components list.

People Search Wire-Frame

Component List

Component NameData SourceExpected ResultsComponent Actions
Search Wrapper 
Search BoxGraph UsersZero to more itemsFilter
Search Clear Clear data & filters
Filter WrapperGraph UsersZero to more items
Filter Combo-boxGraph UsersZero to more itemsFilter
Filter Auto-suggestGraph UsersZero to more itemsFilter
Result WrapperGraph UsersZero to more items
Result CardGraph UserOne itemDisplay
Result User PhotoGraph User PhotoOne itemDisplay
Result User PresenceGraph User PresenceOne itemDisplay
Result User ContactGraph UserOne itemDisplay
Footer WrapperGraph UsersZero to more itemsDisplay

Component Folder Structures

Starting with components, add the following folders under this path:

“~\src\webparts\peopleSearch\components\”

  • filters
  • results
  • search

Next, add blank/empty .TSX files for each component:

~\src\webparts\peopleSearch\components\filters\

  • FilterWrapper.tsx
  • FilterComboBox.tsx
  • FilterAutoSuggest.tsx

~\src\webparts\peopleSearch\components\footer\

  • FooterWrapper.tsx

~\src\webparts\peopleSearch\components\results\

  • ResultWrapper.tsx
  • ResultCard.tsx
  • ResultUserPhoto.tsx
  • ResultUsrPresence.tsx      Not required / built into Persona (Office UI Fabric) control
  • ResultUserContact.tsx

~\src\webparts\peopleSearch\components\search\

  • SearchWrapper.tsx
  • SearchBox.tsx
  • SearchClear.tsx

Even thought these files are empty the project should build without any issues, I still like to build the project after every major change I make.

<em>gulp build</em>

Note: “~\” represents the project’s root folder.

Service, Models & Data Folder Structures

I am going to create the folder structure which will be used by the Service, Models & Data files. Start by adding the following folders under this path: “~\src\”

  • data
  • models
  • services

I have not planned exactly what will be created, but here is an overview as to what will go where:

  • The Data folder will contain .JSON files, these will contain mock data for testing the webpart using the local work bench
  • The Models folder will contain .TS files, which will describe the structure of the data respective of where it is stored or accesses from.
  • The Service folder will contain .TS files and classes that will represent the services and will retrieve data either from the mock or live data sources.

Next Steps

Now that I have my project structure laid out, I can focus on creating either the Data & Services or the Components & User Interface. Neither option is wrong, however, because I know more about the User Interface than the Services, that is where I will begin for my next post.

Tip: If you cannot decide on which order to build your webpart(s) take a look at the “Thinking in React” article, you may also find the section “Step 2: Building A Static Version In React” useful.

People-Search Wire Frame Page3

SharePoint/SPFx: Returning to Webpart Development Part #2

Recently I was asked to develop a webpart for a modern SharePoint site. My first thoughts were; where do I start, I haven’t done any webpart development for years? I would like to share my journey with you over the next few posts and hope my experience will help new and returning developers along the way.

In my previous post I covered:

In this post I will cover:

Avoiding Pitfalls Part #1

Let’s start by addressing the pitfalls I listed in my last post:

1. Distracted by someone else’s code

This one is easy; we are going create a new / blank project. If we need to refer to someone elses code for inspiration, then we will do this outside of our project.

2. Getting bogged down in detail

The React website has a great article on this called Thinking in React which I recommend reading. So, let’s practice what we preach….

3. Avoid the muddying of data and presentation code/layers

Well the plan we made to avoid the previous pitfall will also help with this too. If we are still confused it is because we need to do some more planning… 😊

4. Check the SPFx Project Generator Version

The tooling used to scaffold SPFx project is out of date. This should not be a problem if you have just configured a new brand environment/machine. If, however like me you are coming back to an existing environment/machine then I would recommend uninstalling everything SPFx related:

npm uninstall @microsoft/generator-sharepoint --global
npm uninstall yo --global
npm uninstall gulp --global

And finally, Node.js using the “Add or remove programmes…” to check the version and uninstall if required.

Once done, you can re-install the tools with confidence…

Solution Design (Avoiding Pitfalls Part #2)

Let’s start by creating a wire-frame, which essentially is a design without branding or colours. There are many great tools on the market for creating wire-frames, such as Balsamiq, Lucidchart or Microsoft Visio. However for this example, I am going to use Microsoft PowerPoint to demonstrate how easy it is to create an effective wire-frame. Click here to open my People-Search-Wire-Frame.pdf file.

Wire-Frames

Start by adding the components to the diagram, while thinking about how the end-user would interact with your webpart.

People Search Wire Frame Page 1

On the next diagram I have labelled each control, giving a brief description of each control and / or its behaviour. If you are a solo developer you may decide to skip this detail, however, I find the validation process useful.

People Search Wire Frame Page 2

The last page/diagram breaks the webpart down into components. I have done this by functionality, repeatability and in some cases, where the data will come from.

People Search Wire Frame Page 3

Data Sources

Now that I have a design I can start thinking about where the data is going to come from. In the past I may have used SharePoint Search with the User Profile Service, however today I am going to use the Microsoft Graph API, as “The Graph” combines multiple Microsoft 365 services into a single endpoint.

Tip: The Graph Explorer is a great place to start working Microsoft Graph, it has a number of sample queries to run against dummy data or better still sign in to your Microsoft 365 Tenant and test queries against your own data (see my next tip).

Tip: Sign-up to the Microsoft Developer Programme and get a Microsoft 365 developer subscription to develop your solutions independent of your production environment.

The table below lists the components I expect to build, obviously this may change if I find other complexities once the build is under way, plus:

  • The Data Source gives a rough idea as to where to find the data.
  • The Expected Results gives a rough idea of shape of the data.
  • The Component Action describes what the component will do with the data.
Component NameData SourceExpected ResultsComponent Actions
Search Wrapper
Search BoxGraph UsersZero to more itemsFilter
Search ClearClear data & filters
Filter WrapperGraph UsersZero to more items
Filter Combo-boxGraph UsersZero to more itemsFilter
Filter Auto-suggestGraph UsersZero to more itemsFilter
Result WrapperGraph UsersZero to more items
Result CardGraph UserOne itemDisplay
Result User PhotoGraph User PhotoOne itemDisplay
Result User PresenceGraph User PresenceOne itemDisplay
Result User ContactGraph UserOne itemDisplay
Footer WrapperGraph UsersZero to more itemsDisplay
Components List

Choosing a Framework

Just because you are developing a SPFx webpart does not mean you have to build it in React, there are other options, such as “No JavaScript framework” (i.e. hand-rolled or do it yourself) or Angular.

Sorry to disappoint, however I am going to stick with React – React Hooks possibly with useReducer.

Creating a SPFx Project

To help you reproduce my solution I have listed the steps below.

Creating a VS Code Workspace

I am a fan of Workspaces they enable you to save and share preferences including UK/NZ spellings…

  1. Create your project directory, for example:
    C:\…\Company.SPFx.Webparts.People
  2. Open Visual Studio and navigate to: File -> Open folder…
  3. Next locate and open your new directory
  4. Once opened navigate to: File -> Save Workspace As…
  5. Navigate up a folder, enter “Company.SPFx.Webparts.People.code-workspace” and click save

Scaffold the SPFx Project

Now we are ready to open the Terminal window with VS Code and run the Yeoman SharePoint generator.

  1. Open Terminal: [Ctrl]+[`]
  2. Enter the following commands:
yo @microsoft/sharepoint
  1. Next enter: MS-Graph People Search – Press enter
  2. Select: SharePoint Online only (latest) – press enter
  3. Use the current folder – press enter
  4. Do you want to allow the tenant admin the choice of being able to deploy the solution to all sites immediately without running any feature deployment or adding apps in sites? – Y
  5. Will the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant? N
  6. Select: WebPart – press enter
  7. What is your Web part name? People Search – press enter
  8. What is your Web part description? Search for people within your organisation using Microsoft Graph – press enter
  9. Select: React – press enter

Once the Yeoman command has completed, we can check the solution by running the following commands:

gulp clean
gulp build
npm shrinkwrap
gulp serve

Source Control

I am going to designate source control out of scope for this post, however what I would recommend committing your code (or backing it up) at this point, so that you have a place you can rollback to if it all goes wrong.

Next time

For my next post I will focus on building the structure of my webpart.

Troubleshooting SPFx Webparts: Useful Links

Based upon the App Catolog (Catalogue) being configured with the following URL:
https://<tenant>.sharepoint.com/sites/Apps/

Apps for SharePoint
A catalog to store apps for SharePoint
https://<tenant>.sharepoint.com/sites/Apps/AppCatalog/Forms/AllItems.aspx

Client Side Assets
A library to store client side assets
https://<tenent>.sharepoint.com/sites/Apps/ClientSideAssets/AllItems.aspx

Client Side Component Manifests
A list to store client component manifests
https://<tenent>.harepoint.com/sites/Apps/Lists/ComponentManifests/AllItems.aspx

Configure Visual Studio Code with VSTS

Visual Studio CodeWhile in the process of setting up a new environment I thought I would share the steps I took to configure Visual Studio Code (VS-Code) with Visual Studio Team Services (VSTS) online.

Installation

  1. Navigate to: https://code.visualstudio.com
  2. Select the relevant version for your machine e.g. macOS or Windows x64 and click Download
  3. Double click on the installer, if it doesn’t automatically open, follow the wizard
  4. Open Visual Studio Code (VS-Code)
  5. Click on the Extensions icon (left hand side)
  6. Search for Visual Studio Team Services and click Install

Configuration

  • Click on Source Control icon (left hand side)
  • Click on Initialize Repository icon (top-left hand side)
  • Select a folder in which to store the code. For example: C:\Code\Project
  • Click Initialize Repository
  • You will have two options to authenticate: Manually provide a Key or Automatically provide a key…

Manually create a VSTS access token

If you’re not prompted for your Username and Password, follow these instructions on how to create personal access tokens to authenticate access: https://docs.microsoft.com/en-us/vsts/accounts/use-personal-access-tokens-to-authenticate

For ease of use I would recommend using the Automatic approach, however here is how to manually create a VSTS access token.

    • Sign in to either your VSTS account https://account.visualstudio.com
    • from your home page; click on your profile icon and then security details
    • Click Personal access tokens (left hand side) and Add
    • Enter the following:
      • Description: e.g. Bob’s VS-Code Win 10
      • Expires in: e.g. 90 days
      • Accounts: e.g. select the default
      • Authorized Scopes: e.g. All scopes
      • Click Create Token
      • Make a copy of token, e.g. werwqefslz2hhldesdfwfwvsdafqfq2aadsfdpalaifa5ppuyikuik
      • Back to VS-Code
      • Enter the code…

Supporting information

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