WPF 3D with Helix Toolkit

Helix Toolkit builds on the 3-D functionality in Windows Presentation Foundation (WPF).  This toolkit provides a higher level API for working with 3D in WPF, via a collection of controls and helper classes.

Using the Package Manager Console To install HelixToolkit.Wpf, run the following command in the Package Manager Console.

PM> Install-Package HelixToolkit.Wpf

Using the Nuget UI

To find HelixToolkit in NuGet, follow these steps:
1. Open your project in Visual Studio.
2. Right click on the References folder and select “Manage Nuget Packages…” from the context menu.
3. In the “Manage Nuget Packages” dialog, select “Online” on the right.
4. In the search field, enter “HelixToolkit”.
5. Select the HelixToolkit.Wpf package and press the Install button.

Creating a 3D view

The HelixViewport3D is the object that will contain our 3D scene. This is a WPF control allowing for imperative or declarative coding. Lets create a HelixViewport3D object using C#.

private void Create3DViewPort() { var hVp3D = new HelixViewport3D(); }

Using XAML object creation would look like this.

<code>&lt;Window x:Class="GettingStartedDemo.MainWindow" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:h="http://helix-toolkit.org/wpf"
        Title="Getting Started Demo" Height="480" Width="640"&gt;

     &lt;h:HelixViewport3D &gt;
     &lt;/h:HelixViewport3D&gt;

 &lt;/Window&gt;
</code>

This gives us a 3D space in which to setup our scene and work with 3D objects.

Adding lights

Next we need to add lighting to the HelixViewport3D. Without lighting, objects in the view-port scene will not be visible.

In C#:

<code>private void Create3DViewPort()
{
    var hVp3D = new HelixViewport3D();
    var lights = new DefaultLights();
    hVp3D.Children.Add(lights);
} 
</code>

In XAML:

<code>&lt;h:HelixViewport3D &gt;
     &lt;h:DefaultLights/&gt;
 &lt;/h:HelixViewport3D&gt;
</code>

Adding 3D content

Now that we have light and a view-port we can add a 3D object. Helix Toolkit comes with several 3D objects such as a box, tube, helix, pipe, and of course a teapot. Let’s add the teapot to the view-port.

In C#:

<code> private void Create3DViewPort()
 {
     var hVp3D = new HelixViewport3D();
     var lights = new DefaultLights();
     var teaPot = new Teapot();
     hVp3D.Children.Add(lights);
     hVp3D.Children.Add(teaPot);
  } 
</code>

In XAML:

<code> &lt;h:HelixViewport3D &gt;
      &lt;h:DefaultLights/&gt;
      &lt;h:Teapot/&gt;
 &lt;/h:HelixViewport3D&gt;
</code>

Complete Getting Started Example Code

In C#:

<code>public partial class MainWindow
{
    public MainWindow()
    {
        this.InitializeComponent();
        Create3DViewPort();
    }

    private void Create3DViewPort()
    {
        var hVp3D = new HelixViewport3D();
        var lights = new DefaultLights();
        var teaPot = new Teapot();
        hVp3D.Children.Add(lights);
        hVp3D.Children.Add(teaPot);
        this.AddChild(hVp3D);
    }
}
</code>

In XAML:

<code>&lt;Window x:Class="GettingStartedDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:h="http://helix-toolkit.org/wpf"
        Title="Getting Started Demo" Height="480" Width="640"&gt;

    &lt;h:HelixViewport3D &gt;
        &lt;h:DefaultLights/&gt;
        &lt;h:Teapot/&gt;
    &lt;/h:HelixViewport3D&gt;</code>

Future Versions of JavaScript Frameworks

React

After a 3 months wait, v15.5.0 is released. The team is also busy working towards v16 which is currently in alpha.
You can find React’s Patent clause here. Robert Pierce of El Camino Legal LLP has written this article criticizing Facebook’s patent clause and arguing it is not open source software. Hacker News comments here.

Aurelia

It’s now approaching a whole year since Aurelia reached v1.0.
Following the Early March Mega Release there will be an April update with — aurelia-router 1.3.0
aurelia-templating-resources 1.4.0
aurelia-cli 0.28.0
aurelia-ui-virtualization 1.0.0-beta.3.1.0
aurelia-i18n 1.5.0
and some patch releases
Several other great new Aurelia features are coming in future releases:
New Chrome Debugger
Webpack v2 support
CLI enhancements
Hot module reload
VS Code plugin enhancements
HTML Template Validation
For more details see the Aurelia blog.

Angular 2+

Angular 4 RTM will be released in March 2017! (v4.0.2)
Angular 2 reached RTM on 15th September and reached v2.4.10 before v4.
Since v2 was released, the Google team has mostly met its own proposed schedule on releasing new minor and major versions
Angular 2.1 — Route Preloading
Angular 2.2 — AOT + ngUpgrade
Angular 2.3 — Language Service
Angular 2.4 — “Stability Interjection”
Angular 4 — March 2017

The Google Team have agreed to release new patch versions every week, a new minor version every month and a major version every 6 months.

So this is the plan for new major versions

Angular 5 — Sept/Oct 2017
Angular 6 — March 2018
Angular 7 — Sept/Oct 2018

By new major version we mean new features and potential breaking changes since the last release. So we should not necessarily get overexcited about new major versions, or conflate higher major numbers with very much higher quality.

For full details see Igor Minar’s blog post and opening keynote. Igor makes many interesting points in the keynote.
Google always use the latest version of AngularJS for their own applications. He also mentions TypeScript and the desire to support v2.1.

Some of the new Angular features we can expect by March are:
– Better Compiler Errors
– Faster
– Smaller

Angular 4 is backwards compatible with Angular 2 (but not Angular 1) so Angular 2+ looks to be the better bet for new applications that you will need to maintain and improve over a long lifetime.

For applications that you expect to be one-off releases and need to release very soon, it might still make more sense to use Angular 1.x if your experience is with Angular 1.x and you want to take advantage of the more mature ecosystem that surrounds it, however the case for Angular v2+ over v1 will only grow stronger as time goes on.

The Google team recommends we use the latest version.

Polymer

Polymer v1.9 has been released.
If you haven’t currently invested in Polymer 1.x, I recommend using v2.x instead.
The 4th Release Candidate version of Polymer 2.0 has now been released. A series of videos from Polymer Summit 2016 are available on YouTube.
To learn about the upgrade path to Polymer 2.0 watch Polymer 2.0 in 2.0 seconds. To understand how it works see Polymer 2.0: Under the Hood. Rob Dodson describes Polymer as an opinionated usage of Web Components.

Ember

Ember v2.12 and v2.13 Beta are out

Full-Stack MVC Application Development with AngularJS

These days, developers are interested to use AngularJS and ASP.NET MVC (wiring MVC and AngularJS). So in this post we will learn how to combine the best of both worlds and use the goodness of AngularJS in ASP.NET MVC. 

To start, let’s create ASP.NET MVC application and right click on the MVC project. From the context menu, click on Manage Nuget Package. Search for the AngularJS package and install into the project.

After successfully adding the AnngularJS library, you can find those files inside the Scripts folders.

Reference of AngularJS library

You have two options to add an AngularJS library reference in the project: MVC minification and bundling or by adding AngularJS in the Script section of an individual view. If you use bundling, then AngularJS will be available in the whole project. However you have the option to use AngularJS on a particular view as well.

Let’s say you want to use AngularJS on a particular view (Index.cshtml) of the Home controller. First you need to refer to the AngularJS library inside the scripts section as shown below:

@section scripts{

    <script src=”~/Scripts/angular.js”>script>

}

Next, apply the ng-app directive and any other required directives on the HTML element as shown below:

<div ng-app=”” class=”row”>

     <input type=”text” ng-model=”name” />

     {{name}}

div>

When you run the application you will find AngularJS is up and running in the Index view. In this approach you will not be able to use AngularJS on the other views because the AngularJS library is only referenced in the Index view.

You may have a requirement to use AngularJS in the whole MVC application. In this case, it’s better to use bundling and minification of MVC and all the AngularJS libraries at the layout level. To do this, open BundleConfig.cs from the App_Start folder and add a bundle for the AngularJS library as shown below:

  public static void RegisterBundles(BundleCollection bundles)

        {

            bundles.Add(new ScriptBundle(“~/bundles/angular”).Include(

                        “~/Scripts/angular.js”));

 

After adding the bundle in the BundleConfig file, next you need to add the AngularJS bundle in the _Layout.cshtml as listed below:

<head>

    <meta charset=”utf-8″ />

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>@ViewBag.Title – My ASP.NET Applicationtitle>

    @Styles.Render(“~/Content/css”)

    @Scripts.Render(“~/bundles/modernizr”)

    @Scripts.Render(“~/bundles/angular”)

    @Scripts.Render(“~/bundles/jquery”)

    @Scripts.Render(“~/bundles/bootstrap”)

    @RenderSection(“scripts”, required: false)

head>

After creating an AngularJS bundle and referring to it in _Layout.cshtml, you should be able to use AngularJS in the entire application.

 

Performance of JavaScript Frameworks

Technical

Size (minified, not gzipped)

React+Redux — 156k or 167k with plugins
Angular 1 – 158k minimum, 240k with router, HTTP and animation system
Polymer — 222k minimum, 302k (spec compliant)
Aurelia — 252k minimum, 302k with standard plugin
Ember — 435k including router
Angular 2 — 698k minimum, 919k with RxJS, 1023k with RxJS and router and HTTP client

(Not that Redux is in any way large, but it is unfair to add Redux to the file size for React only. Redux happens to be more commonly used by React users, but it is an optional extra regardless of which framework you choose.)

Rob mentions that the Angular team are using tree shaking to reduce the file size.

Latest Performance Developments 

The dbmon tool to measure the performance was popularised by Ryan Florence from Facebook in his talk at Conf 2015 showing React was faster than Angular 1 and much faster than Ember back in 2015.

The dbmon test has recently been updated with adjustable mutations percentage. This is the latest performance results using this tool:

React — 52 to 54fps
Angular — 45 to 46fps
Angular 2– 49 to 52fps

Only naive implementations for Polymer and Ember are currently available
Polymer 1.8 — 44–46 fps
Polymer 2.0 –37 to 40 fps
Ember — 44–46 fps

Some other selected framework/technology results:
Vue — 51–53 fps
Vue 2–41 to 44fps
Elm — 51 to 53fps
Inferno — 54 to 56fps
Vanilla JS varies from 50 to 72 fps

 

Full-Stack MVC Application with Redux

This post covers the end-to-end process (wiring MVC and React) of creating a brand new ASP.NET MVC website and adding a React component in it. We will start from scratch and end with a fully functioning component.

We can use .NET Framework, but you can instead use .NET Core if you want to be able to run your site on Linux or Mac OS. Currently .NET Core is missing some of the functionality provided by .NET Framework, so it is recommended to use .NET Framework unless you have a reason to use .NET Core specifically (eg. cross-platform support).

Start by creating a new ASP.NET Core MVC project:

  1. File → New → Project
  2. Ensure “.NET Framework 4.6” is selected in the dropdown list at the top
  3. Go to Templates → Visual C# → Web and select the “ASP.NET Core Web Application (.NET Framework)” template. 

We need to install ReactJS.NET to the newly-created project. This is accomplished using NuGet, a package manager for .NET. Right-click on your project in the Solution Explorer and select “Manage NuGet Packages”. Click the “Browse” tab, search for “React.AspNet”, and install the React.AspNet package.

We also need to modify the Startup.cs file to initialize ReactJS.NET. Open Startup.cs and perform the following changes:

At the top of the file, add:

<code class="csharp language-csharp" data-lang="csharp"><span class="k">using</span> <span class="nn">Microsoft.AspNetCore.Http</span><span class="p">;</span>
<span class="k">using</span> <span class="nn">React.AspNet</span><span class="p">;</span>
</code>

Directly above:

<code class="csharp language-csharp" data-lang="csharp"><span class="c1">// Add framework services.</span>
<span class="n">services</span><span class="p">.</span><span class="n">AddMvc</span><span class="p">();</span>
</code>

Add:

<code class="csharp language-csharp" data-lang="csharp"><span class="n">services</span><span class="p">.</span><span class="n">AddSingleton</span><span class="p">&lt;</span><span class="n">IHttpContextAccessor</span><span class="p">,</span> <span class="n">HttpContextAccessor</span><span class="p">&gt;();</span>
<span class="n">services</span><span class="p">.</span><span class="n">AddReact</span><span class="p">();</span>
</code>

Directly above:

<code class="csharp language-csharp" data-lang="csharp"><span class="n">app</span><span class="p">.</span><span class="n">UseStaticFiles</span><span class="p">();</span>
</code>

Add:

<code class="csharp language-csharp" data-lang="csharp"><span class="c1">// Initialise ReactJS.NET. Must be before static files.</span>
<span class="n">app</span><span class="p">.</span><span class="n">UseReact</span><span class="p">(</span><span class="n">config</span> <span class="p">=&gt;</span>
<span class="p">{</span>
  <span class="c1">// If you want to use server-side rendering of React components,</span>
  <span class="c1">// add all the necessary JavaScript files here. This includes</span>
  <span class="c1">// your components as well as all of their dependencies.</span>
  <span class="c1">// See http://reactjs.net/ for more information. Example:</span>
  <span class="c1">//config</span>
  <span class="c1">//  .AddScript("~/Scripts/First.jsx")</span>
  <span class="c1">//  .AddScript("~/Scripts/Second.jsx");</span>

  <span class="c1">// If you use an external build too (for example, Babel, Webpack,</span>
  <span class="c1">// Browserify or Gulp), you can improve performance by disabling</span>
  <span class="c1">// ReactJS.NET's version of Babel and loading the pre-transpiled</span>
  <span class="c1">// scripts. Example:</span>
  <span class="c1">//config</span>
  <span class="c1">//  .SetLoadBabel(false)</span>
  <span class="c1">//  .AddScriptWithoutTransform("~/Scripts/bundle.server.js");</span>
<span class="p">});</span>
</code>

Finally, add this to Views\_ViewImports.cshtml:

<code class="csharp language-csharp" data-lang="csharp"><span class="n">@using</span> <span class="n">React</span><span class="p">.</span><span class="n">AspNet</span></code>

 

Choosing a JavaScript Framework

Choosing a JavaScript Framework has been never an easy decision because there is so much to consider.

Rob Eisenberg is a JavaScript framework expert. He is the mechanic behind Caliburn.Micro, Durandal and Aurelia, and has also worked on the Angular 2.0 and Angular Material teams. This post was originally written as a summary of Rob’s talk. 

The frameworks under the spotlight are:

Angular 1.x
Angular 2 (Angular 2+)
Aurelia
Ember
Polymer
React

Angular 1.x is an all-in-one framework. Rob says it is pretty much deprecated, there’s literally a fixed number of months left on the lifetime of that framework
and it’s probably fair to say that you shouldn’t start a new project in Angular JS right now, and you should be thinking about how you might migrate any existing code bases.

Rob describes Angular 2, Aurelia, Ember and Polymer as also All-in-one frameworks, but modern ones.

React is not a framework, per se. It’s a view rendering engine or a component model.

Rob recommends Visual Studio Code and is using it on his Mac. 

For a very simple Hello World application, we will compare these frameworks:

Angular 1.x
index.html is 13 lines of code
We see the ng-controller and ng-model directives.
app.js is 8 lines of code.

Rob describes this as a throwback to the previous generation of frameworks: Angular specific modules rather than ES2015 modules. He describes the Angular 1 two way data-binding model.
(As of Angular 1.5 we have Angular Components as a superior alternative to using controllers and directives.)

Angular 2
Rob says Angular 2 really focuses on TypeScript, and it is much more difficult to use plain JavaScript so most people are going to be kind of pushed down the TypeScript road necessarily with Angular 2 (The equivalent documentation is available for TypeScript, JavaScript and Dart. Judge for yourself how much more difficult it is to use with plain JavaScript)
index.html is 32 lines of code
(I could not believe that there isn’t a simpler way to write this in Angular 2. Rob has found some Angular 2 documentation that pulls in a whole load of modules. For the purposes of developing a hello world type app, Rob is pulling in the following modules:
es6-shim
system-polyfills.js
shims for IE.js
angular2-polyfills.js (no longer part of the Angular2 RC)
system.src.js
Rx.js
angular.dev.js
There is also a bunch of code for here configuring a System JS module loader. System JS is written by Guy Bedford and Max Norlund and has nothing to do with Angular 2)
main.ts — 4 lines
app.component.ts — 20 lines

Rob explains the Angular2 decorator. He uses an inline template rather than using a template URL. He also explains two-way data-binding in Angular2, and points out that Google have deviated from the HTML specification by using mixed casing.

Aurelia
index.html — 10 lines. This imports System JS and uses it to import the Aurelia bootstrapper.
app.js — 8 lines
app.html — a template with 5 lines of code. Rob explains the two way data binding mechanism used here.

Ember
index.html — 16 lines. Imports jquery, handlebars, ember and app.js
app.js — 23 lines.

Rob says Ember is a very strict MVC paradigm and requires a router even for Hello World.

Polymer
index.html — 10 lines.
my-app.html — 22 lines including template, a script block and 4 blank lines.

Rob says the web components centric philosophy concerns him because it doesn’t make sense to do everything in HTML but there it is, that’s my opinion
Rob likens Polymer to the long forgotten Microsoft Acropolis project from 2008 which tried to do everything in XAML.

React
index.html — 13 lines, importing es5-shim, es5-sham and console-polyfill
app.js — 39 lines.

ASP.NET MVC and Redux

When we at Spoil decided to roll out our mobile app, one of the first decisions we had to make was: what language do we use? After some deliberation, the decision was made: React-Native it was going to be. Learning a new “language” or framework isn’t a huge issue. 

React-Native and Redux?

As soon as you start learning about react-native (or react), you start to understand state vs props, you know what componentDidMount does and you even understand how to properly create your components so they are re-usable. Now all of a sudden you found yourself talking about stores, reducer compositions, actions and mapping state to props.

Some Analogies

If you are coming from an MVC (or MVVC) world, you are used to models, views and controllers. However in Redux we are dealing with actions, reducers, stores and components. Trying to “translate” MVC to Redux is tricky but here is how I would do it:

Actions = Controller. Think of your actions as the controller. Whenever you want something to happen in your app (i.e. load some data, change a isLoading flag from true to false…) you will have to dispatch an action. Just like in MVC where you would have to call a controller endpoint.

Reducer = Model. Sort of. Your reducers will be in charge of holding the current state of your application (i.e. user info, information loaded from the api, items you want to display…). It will also be the part that decides what to do when an action is called. While in MVC you might have a model with the method setName(), with Redux you would have a reducer handle an action to set the name in the state.

Stores = ???. The store is Redux specific and doesn’t really have an equivalent in MVC. Not to worry though. This part is taken care off behind the scenes. The store is like a container for the state that aggregates all of the reducers. It has a method to the get the current state, and exposes ways to subscribe to the state changes (using the “connect()” method). This is what will allow you to call actions and pass them in as props to your components.

Components = Views. Components are kind of like your smart views. They display the information that they get from the state. I recommend splitting up your components into two parts. One just for the presentational part (dumb components) and one to handle all of the actions and state changes (smart components).

Moving From MVC Thinking to Redux Thinking

One of the main differences between MVC and Redux is that, while in MVC data can flow in a bidirectional manner, in Redux it strictly moves in one direction.

With Redux things work a little differently. Let’s say you have a component and you want to do something when a button gets pressed. Where do you start? 

  1. Define your Action
  2. Define your Reducer
  3. Define the Actions as a Prop in your Component
  4. Wire it up in your View

 

.NET Core Angular Templates

The latest tooling in Visual Studio for .NET Core will be pretty good. Fortunately, the dotnet sdk, and subsequently the CLI, have libraries available for various Single Page Application framework quick starts.

With the latest version of Visual Studio 2015+ installed, you should have the dotnet core SDK version 1.0.3 installed. If not, you can download the SDK.

The “dotnet –info” command can be used to confirm SDK version. 

To get started with “dotnet new” (new being the command to create new projects), the SPA templates for Angular and other various frameworks can be utilized after installing this package:

dotnet new –install Microsoft.AspNetCore.SpaTemplates::*

This will run for a bit and install various dependencies. After installation is complete, the available templates can be viewed by running “dotnet new” by itself.

By using this template, you get a nice base starting point for an Angular application. Some of the niceties are having the build process already configured for bundling, minification, and various dependencies already configured.

Webpack, TypeScript, and other things will appear already configured when the project is opened in future version of Visual Studio 2015+.

Running the project for the first time can take a bit of time since all of the npm packages and such are pulled down. But, the template does have a few little niceties and is a fully working Angular project. The “Hello, world!” view has some nice information about the template and details some parts of the technology used in the template.

Web API Pros and Cons

With the new changes to the Web API, there has been a lot of discussion of where the new Web API technology fits in the ASP.NET Web stack. There are a lot of choices to build HTTP based applications available now on the stack – we’ve come a long way from when WebForms and Http Handlers/Modules where the only real options. Today we have WebForms, MVC, ASP.NET Web Pages, ASP.NET AJAX, WCF REST and now Web API as well as the core ASP.NET runtime to choose to build HTTP content with.

Web API definitely squarely addresses the ‘API’ aspect – building consumable services – rather than HTML content, but even to that end there are a lot of choices you have today. So where does Web API fit, and when doesn’t it?

 

What is a Web API?

HTTP ‘APIs’ are becoming increasingly more important with the rise of the many devices in use today. Most mobile devices like phones and tablets run Apps that are using data retrieved from the Web over HTTP. Desktop applications are also moving in this direction with more and more online content and syncing moving into even traditional desktop applications. The pending Windows 8 release promises an app like platform for both the desktop and other devices, that also emphasizes consuming data from the Cloud.

Likewise many Web browser hosted applications these days are relying on rich client functionality to create and manipulate the browser user interface, using AJAX rather than server generated HTML data to load up the user interface with data.

These mobile or rich Web applications use their HTTP connection to return data rather than HTML markup in the form of JSON or XML typically. But an API can also serve other kinds of data, like images or other binary files, or even text data and HTML (although that’s less common). A Web API is what feeds rich applications with data.

ASP.NET Web API aims to service this particular segment of Web development by providing easy semantics to route and handle incoming requests and an easy to use platform to serve HTTP data in just about any content format you choose to create and serve from the server.

 The .NET stack already includes a number of technologies that provide the ability to create HTTP service back ends, and it has done so since the very beginnings of the .NET platform. From raw HTTP Handlers and Modules in the core ASP.NET runtime, to high level platforms like ASP.NET MVC, Web Forms, ASP.NET AJAX and the WCF REST engine (which technically is not ASP.NET, but can integrate with it), you’ve always been able to handle just about any kind of HTTP request and response with ASP.NET. The beauty of the raw ASP.NET platform is that it provides you everything you need to build just about any type of HTTP application you can dream up from low level APIs/custom engines to high level HTML generation engine. ASP.NET as a core platform clearly has stood the test of time 10+ years later and all other frameworks like Web API are built on top of this ASP.NET core.

However, although it’s possible to create Web APIs / Services using any of the existing out of box .NET technologies, none of them have been a really nice fit for building arbitrary HTTP based APIs. Sure, you can use an HttpHandler to create just about anything, but you have to build a lot of plumbing to build something more complex like a comprehensive API that serves a variety of requests, handles multiple output formats and can easily pass data up to the server in a variety of ways. Likewise you can use ASP.NET MVC to handle routing and creating content in various formats fairly easily, but it doesn’t provide a great way to automatically negotiate content types and serve various content formats directly (it’s possible to do with some plumbing code of your own but not built in). Prior to Web API, Microsoft’s main push for HTTP services has been WCF REST, which was always an awkward technology that had a severe personality conflict, not being clear on whether it wanted to be part of WCF or purely a separate technology. In the end it didn’t do either WCF compatibility or WCF agnostic pure HTTP operation very well, which made for a very developer-unfriendly environment.

ASP.NET Web API differentiates itself from the previous Microsoft in-box HTTP service solutions in that it was built from the ground up around the HTTP protocol and its messaging semantics. Unlike WCF REST or ASP.NET AJAX with ASMX, it’s a brand new platform rather than bolted on technology that is supposed to work in the context of an existing framework. The strength of the new ASP.NET Web API is that it combines the best features of the platforms that came before it, to provide a comprehensive and very usable HTTP platform. Because it’s based on ASP.NET and borrows a lot of concepts from ASP.NET MVC, Web API should be immediately familiar and comfortable to most ASP.NET developers.

Here are some of the features that Web API provides:

  • Strong Support for URL Routing to produce clean URLs using familiar MVC style routing semantics
  • Content Negotiation based on Accept headers for request and response serialization
  • Support for a host of supported output formats including JSON, XML, ATOM
  • Strong default support for REST semantics but they are optional
  • Easily extensible Formatter support to add new input/output types
  • Deep support for more advanced HTTP features via HttpResponseMessage and HttpRequestMessage
    classes and strongly typed Enums to describe many HTTP operations
  • Convention based design that drives you into doing the right thing for HTTP Services
  • Very extensible, based on MVC like extensibility model of Formatters and Filters
  • Self-hostable in non-Web applications 
  • Testable using testing concepts similar to MVC

Web API is meant to handle any kind of HTTP input and produce output and status codes using the full spectrum of HTTP functionality available in a straight forward and flexible manner.

Looking at the list above you can see that a lot of functionality is very similar to ASP.NET MVC, so many ASP.NET developers should feel quite comfortable with the concepts of Web API. The Routing and core infrastructure of Web API are very similar to how MVC works providing many of the benefits of MVC, but with focus on HTTP access and manipulation in Controller methods rather than HTML generation in MVC.

There’s much improved support for content negotiation based on HTTP Accept headers with the framework capable of detecting automatically what content the client is sending and requesting and serving the appropriate data format in return. This seems like such a little and obvious thing, but it’s really important. Today’s service backends often are used by multiple clients/applications and being able to choose the right data format for what fits best for the client is very important.

While previous solutions were able to accomplish this using a variety of mixed features of WCF and ASP.NET, Web API combines all this functionality into a single robust server side HTTP framework that intrinsically understands the HTTP semantics and subtly drives you in the right direction for most operations. And when you need to customize or do something that is not built in, there are lots of hooks and overrides for most behaviors, and even many low level hook points that allow you to plug in custom functionality with relatively little effort.

If your primary focus of an application or even a part of an application is some sort of API then Web API makes great sense.

HTTP Services
If you’re building a comprehensive HTTP API that is to be consumed over the Web, Web API is a perfect fit. You can isolate the logic in Web API and build your application as a service breaking out the logic into controllers as needed. Because the primary interface is the service there’s no confusion of what should go where (MVC or API). Perfect fit.

Primary AJAX Backends
If you’re building rich client Web applications that are relying heavily on AJAX callbacks to serve its data, Web API is also a slam dunk. Again because much if not most of the business logic will probably end up in your Web API service logic, there’s no confusion over where logic should go and there’s no duplication. In Single Page Applications (SPA), typically there’s very little HTML based logic served other than bringing up a shell UI and then filling the data from the server with AJAX which means the business logic required for data retrieval and data acceptance and validation too lives in the Web API. Perfect fit.

Generic HTTP Endpoints
Another good fit are generic HTTP endpoints that to serve data or handle ‘utility’ type functionality in typical Web applications. If you need to implement an image server, or an upload handler in the past I’d implement that as an HTTP handler. With Web API you now have a well defined place where you can implement these types of generic ‘services’ in a location that can easily add endpoints (via Controller methods) or separated out as more full featured APIs. Granted this could be done with MVC as well, but Web API seems a clearer and more well defined place to store generic application services. This is one thing I used to do a lot of in my own libraries and Web API addresses this nicely. Great fit.

 

Mixed HTML and AJAX Applications: Not a clear Choice 

For all the commonality that Web API and MVC share they are fundamentally different platforms that are independent of each other. A lot of people have asked when does it make sense to use MVC vs. Web API when you’re dealing with typical Web application that creates HTML and also uses AJAX functionality for rich functionality. While it’s easy to say that all ‘service’/AJAX logic should go into a Web API and all HTML related generation into MVC, that can often result in a lot of code duplication. Also MVC supports JSON and XML result data fairly easily as well so there’s some confusion where that ‘trigger point’ is of when you should switch to Web API vs. just implementing functionality as part of MVC controllers.

Ultimately there’s a tradeoff between isolation of functionality and duplication. A good rule of thumb I think works is that if a large chunk of the application’s functionality serves data Web API is a good choice, but if you have a couple of small AJAX requests to serve data to a grid or autocomplete box it’d be overkill to separate out that logic into a separate Web API controller. Web API does add overhead to your application (it’s yet another framework that sits on top of core ASP.NET) so it should be worth it

Keep in mind that MVC can generate HTML and JSON/XML and just about any other content easily and that functionality is not going away, so just because you Web API is there it doesn’t mean you have to use it. Web API is not a full replacement for MVC obviously either since there’s not the same level of support to feed HTML from Web API controllers (although you can host a RazorEngine easily enough if you really want to go that route) so if you’re HTML is part of your API or application in general MVC is still a better choice either alone or in combination with Web API.

 

Some Issues about Web API

Web API is similar to MVC but not the Same

Although Web API looks a lot like MVC it’s not the same and some common functionality of MVC behaves differently in Web API. For example, the way single POST variables are handled is different than MVC and doesn’t lend itself particularly well to some AJAX scenarios with POST data.

Code Duplication

If you build an MVC application that also exposes a Web API it’s quite likely that you end up duplicating a bunch of code and – potentially – infrastructure. You may have to create authentication logic both for an HTML application and for the Web API which might need something different altogether. More often than not though the same logic is used, and there’s no easy way to share. If you implement an MVC ActionFilter and you want that same functionality in your Web API you’ll end up creating the filter twice.

 

Conclusion

Web API is a great new addition to the ASP.NET platform and it addresses a serious need for consolidation of a lot of half-baked HTTP service API technologies that came before it. Web API feels ‘right’, and hits the right combination of usability and flexibility at least for me and it’s a good fit for true API scenarios. However, just because a new platform is available it doesn’t mean that other tools or tech that came before it should be discarded or even upgraded to the new platform. There’s nothing wrong with continuing to use MVC controller methods to handle API tasks if that’s what your app is running now – there’s very little to be gained by upgrading to Web API just because. But going forward Web API clearly is the way to go, when building HTTP data interfaces.

AngularJS (2+) Routing on Visual Studio (2015+)

This post shows how to configure Angular 2+ Routing on an ASP.Net MVC web application in Visual Studio 2015+

Step 1 – Make sure you have installed the prerequisites

Visual Studio 2015+
TypeScript 2.0 

Step 2 – Create ASP.NET MVC Web Application

Go to Visual Studio’s File New Project menu, expand the Web category, and pick ASP.NET Web Application 

Select the template MVC:

Step 3 – Configure Angular 2+

We need now to prepare our frontend to run Angular 2+

Create tsconfig.json which is the TypeScript compiler configuration file.

<span class="js__brace">{</span> 
  <span class="js__string">"compilerOptions"</span>: <span class="js__brace">{</span> 
    <span class="js__string">"target"</span>: <span class="js__string">"es5"</span>, 
    <span class="js__string">"module"</span>: <span class="js__string">"commonjs"</span>, 
    <span class="js__string">"moduleResolution"</span>: <span class="js__string">"node"</span>, 
    <span class="js__string">"sourceMap"</span>: true, 
    <span class="js__string">"emitDecoratorMetadata"</span>: true, 
    <span class="js__string">"experimentalDecorators"</span>: true, 
    <span class="js__string">"lib"</span>: [ <span class="js__string">"es2015"</span>, <span class="js__string">"dom"</span> ], 
    <span class="js__string">"noImplicitAny"</span>: true, 
    <span class="js__string">"suppressImplicitAnyIndexErrors"</span>: true 
  <span class="js__brace">}</span> 
<span class="js__brace">}</span> <br />Add package.json file to your project folder with the below code:<br />The most important things in your package.json are the name and version fields. <br />Those are actually required, and your package won't install without them. <br />The name and version together form an identifier that is assumed to be completely unique. <br />Changes to the package should come along with changes to the version.<br /><br />
<span class="js__brace">{</span> 
  <span class="js__string">"name"</span>: <span class="js__string">"angular-quickstart"</span>, 
  <span class="js__string">"version"</span>: <span class="js__string">"1.0.0"</span>, 
  <span class="js__string">"description"</span>: <span class="js__string">"QuickStart package.json from the documentation for visual studio 2015+ &amp; WebApi"</span>, 
  <span class="js__string">"scripts"</span>: <span class="js__brace">{</span> 
    <span class="js__string">"start"</span>: <span class="js__string">"tsc &amp;&amp; concurrently \"tsc -w\" \"lite-server\" "</span>, 
    <span class="js__string">"lint"</span>: <span class="js__string">"tslint ./app/**/*.ts -t verbose"</span>, 
    <span class="js__string">"lite"</span>: <span class="js__string">"lite-server"</span>, 
    <span class="js__string">"pree2e"</span>: <span class="js__string">"webdriver-manager update"</span>, 
    <span class="js__string">"test"</span>: <span class="js__string">"tsc &amp;&amp; concurrently \"tsc -w\" \"karma start karma.conf.js\""</span>, 
    <span class="js__string">"test-once"</span>: <span class="js__string">"tsc &amp;&amp; karma start karma.conf.js --single-run"</span>, 
    <span class="js__string">"tsc"</span>: <span class="js__string">"tsc"</span>, 
    <span class="js__string">"tsc:w"</span>: <span class="js__string">"tsc -w"</span> 
  <span class="js__brace">}</span>, 
  <span class="js__string">"keywords"</span>: [], 
  <span class="js__string">"author"</span>: <span class="js__string">""</span>, 
  <span class="js__string">"license"</span>: <span class="js__string">"MIT"</span>, 
  <span class="js__string">"dependencies"</span>: <span class="js__brace">{</span> 
    <span class="js__string">"@angular/common"</span>: <span class="js__string">"Version#"</span>, 
    <span class="js__string">"@angular/compiler"</span>: <span class="js__string">"Version#"</span>, 
    <span class="js__string">"@angular/core"</span>: <span class="js__string">"Version#"</span>, 
    <span class="js__string">"@angular/forms"</span>: <span class="js__string">"Version#"</span>, 
    <span class="js__string">"@angular/http"</span>: <span class="js__string">"Version#"</span>, 
    <span class="js__string">"@angular/platform-browser"</span>: <span class="js__string">"Version#"</span>, 
    <span class="js__string">"@angular/platform-browser-dynamic"</span>: <span class="js__string">"Version#"</span>, 
    <span class="js__string">"@angular/router"</span>: <span class="js__string">"Version#"</span>, 
 
    <span class="js__string">"angular-in-memory-web-api"</span>: <span class="js__string">"~0.2.4"</span>, 
    <span class="js__string">"systemjs"</span>: <span class="js__string">"0.19.40"</span>, 
    <span class="js__string">"core-js"</span>: <span class="js__string">"^2.4.1"</span>, 
    <span class="js__string">"rxjs"</span>: <span class="js__string">"5.0.1"</span>, 
    <span class="js__string">"zone.js"</span>: <span class="js__string">"^0.7.4"</span> 
  <span class="js__brace">}</span>, 
  <span class="js__string">"devDependencies"</span>: <span class="js__brace">{</span> 
    <span class="js__string">"concurrently"</span>: <span class="js__string">"^3.2.0"</span>, 
    <span class="js__string">"lite-server"</span>: <span class="js__string">"^2.2.2"</span>, 
    <span class="js__string">"typescript"</span>: <span class="js__string">"~2.0.10"</span>, 
 
    <span class="js__string">"canonical-path"</span>: <span class="js__string">"0.0.2"</span>, 
    <span class="js__string">"tslint"</span>: <span class="js__string">"^3.15.1"</span>, 
    <span class="js__string">"lodash"</span>: <span class="js__string">"^4.16.4"</span>, 
    <span class="js__string">"jasmine-core"</span>: <span class="js__string">"~2.4.1"</span>, 
    <span class="js__string">"karma"</span>: <span class="js__string">"^1.3.0"</span>, 
    <span class="js__string">"karma-chrome-launcher"</span>: <span class="js__string">"^2.0.0"</span>, 
    <span class="js__string">"karma-cli"</span>: <span class="js__string">"^1.0.1"</span>, 
    <span class="js__string">"karma-jasmine"</span>: <span class="js__string">"^1.0.2"</span>, 
    <span class="js__string">"karma-jasmine-html-reporter"</span>: <span class="js__string">"^0.2.2"</span>, 
    <span class="js__string">"protractor"</span>: <span class="js__string">"~4.0.14"</span>, 
    <span class="js__string">"rimraf"</span>: <span class="js__string">"^2.5.4"</span>, 
 
    <span class="js__string">"@types/node"</span>: <span class="js__string">"^6.0.46"</span>, 
    <span class="js__string">"@types/jasmine"</span>: <span class="js__string">"2.5.36"</span> 
  <span class="js__brace">}</span>, 
  <span class="js__string">"repository"</span>: <span class="js__brace">{</span><span class="js__brace">}</span> 
<span class="js__brace">}<br /><br />Create a sub-folder app on the root folder. On this folder we need to create our typescript files: <br />- main.ts<br />- app.module.ts<br />- app.component.ts<br />- app.component.html<br />- need to create also components to each route we need. <br />On this example we need to create two components Roo1Component and Root2Component that must be declares on app.module.ts</span> <br /><br />Create your index.html<br /><br />
<span class="html__doctype">&lt;!DOCTYPE html&gt;</span> 
<span class="html__tag_start">&lt;html</span><span class="html__tag_start">&gt; 
</span><span class="html__tag_start">&lt;head</span><span class="html__tag_start">&gt; 
</span>    <span class="html__tag_start">&lt;script</span><span class="html__tag_start">&gt;</span>document.write('<span class="html__tag_start">&lt;base</span> <span class="html__attr_name">href</span>=<span class="html__attr_value">"' + document.location + '"</span> <span class="html__tag_start">/&gt;</span>');<span class="html__tag_end">&lt;/script&gt;</span> 
    <span class="html__tag_start">&lt;title</span><span class="html__tag_start">&gt;</span>Angular2+ Routing<span class="html__tag_end">&lt;/title&gt;</span> 
    <span class="html__tag_start">&lt;base</span> <span class="html__attr_name">href</span>=<span class="html__attr_value">"/"</span><span class="html__tag_start">&gt; 
</span>    <span class="html__tag_start">&lt;meta</span> <span class="html__attr_name">charset</span>=<span class="html__attr_value">"UTF-8"</span><span class="html__tag_start">&gt; 
</span>    <span class="html__tag_start">&lt;meta</span> <span class="html__attr_name">name</span>=<span class="html__attr_value">"viewport"</span> <span class="html__attr_name">content</span>=<span class="html__attr_value">"width=device-width, initial-scale=1"</span><span class="html__tag_start">&gt; 
</span>    <span class="html__tag_start">&lt;base</span> <span class="html__attr_name">href</span>=<span class="html__attr_value">"/"</span><span class="html__tag_start">&gt; 
</span>    <span class="html__tag_start">&lt;link</span> <span class="html__attr_name">rel</span>=<span class="html__attr_value">"stylesheet"</span> <span class="html__attr_name">href</span>=<span class="html__attr_value">"styles.css"</span><span class="html__tag_start">&gt; 
</span> 
    <span class="html__comment">&lt;!-- load bootstrap 3 styles --&gt;</span> 
    <span class="html__tag_start">&lt;link</span> <span class="html__attr_name">href</span>=<span class="html__attr_value">"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"</span> <span class="html__attr_name">rel</span>=<span class="html__attr_value">"stylesheet"</span><span class="html__tag_start">&gt; 
</span> 
 
    <span class="html__comment">&lt;!-- Polyfill(s) for older browsers --&gt;</span> 
    <span class="html__tag_start">&lt;script</span> <span class="html__attr_name">src</span>=<span class="html__attr_value">"node_modules/core-js/client/shim.min.js"</span><span class="html__tag_start">&gt;</span><span class="html__tag_end">&lt;/script&gt;</span> 
    <span class="html__tag_start">&lt;script</span> <span class="html__attr_name">src</span>=<span class="html__attr_value">"node_modules/zone.js/dist/zone.js"</span><span class="html__tag_start">&gt;</span><span class="html__tag_end">&lt;/script&gt;</span> 
    <span class="html__tag_start">&lt;script</span> <span class="html__attr_name">src</span>=<span class="html__attr_value">"node_modules/systemjs/dist/system.src.js"</span><span class="html__tag_start">&gt;</span><span class="html__tag_end">&lt;/script&gt;</span> 
 
    <span class="html__tag_start">&lt;script</span> <span class="html__attr_name">src</span>=<span class="html__attr_value">"systemjs.config.js"</span><span class="html__tag_start">&gt;</span><span class="html__tag_end">&lt;/script&gt;</span> 
    <span class="html__tag_start">&lt;script</span><span class="html__tag_start">&gt; 
</span>        System.import('app/main.js').catch(function (err) { console.error(err); }); 
    <span class="html__tag_end">&lt;/script&gt;</span> 
 
<span class="html__tag_end">&lt;/head&gt;</span> 
<span class="html__tag_start">&lt;body</span><span class="html__tag_start">&gt; 
</span>    <span class="html__tag_start">&lt;my</span>-app<span class="html__tag_start">&gt;</span>Loading App&lt;/my-app&gt; 
<span class="html__tag_end">&lt;/body&gt;</span> 
<span class="html__tag_end">&lt;/html&gt;</span> <br /><br />Angular will launch the app in the browser with our component and places it in a specific location on index.html.

Copyright © All Rights Reserved - C# Learners