Sunday, April 26, 2015

Angular 2 Hello World using latest alpha

I previously blogged on how to create a Hello World application using Angular 2 Alpha 14. Since then there were some significant changes and that blog is not valid any more.

In this blog I will provide the latest Hello World code using a Component and a View.

Here is the View code

<html>
<head>
    <title>Angular 2 Hello World</title>
    <script src="https://github.jspm.io/jmcriffey/bower-traceur-runtime@0.0.87/traceur-runtime.js"></script>
    <script src="https://jspm.io/system@0.16.js"></script>
    <script src="https://code.angularjs.org/2.0.0-alpha.20/angular2.js"></script>
</head>
<body>
    <my-app></my-app>

    <script>
    System.config({
     traceurOptions: {
       annotations: true,
       memberVariables: true,
       types: true
     },
     paths: {
       '*': '*.js',
       'angular2/*': 'angular2/*'
     }
   });
   System.import('app');
    </script>

</body>
</html>

Here is the Component code

import {Component, View, bootstrap} from 'angular2/angular2';
// Annotation section
@Component({
  selector: 'my-app'
})
@View({
  template: `<h1>Hello {{ name }}</h1>`
})
// Component controller
class App {
  constructor() {
      this.name = 'World';
  }
}

bootstrap(App);

I created a plnkr with the above code.

You can also download the Visual Studio 2015 and Visual Studio 2013 solutions from my GitHub site

Visual Studio 2013 version

Visual Studio 2015 version


Tuesday, April 21, 2015

Angular 2 Hello World using Visual Studio


Here is the quickstart for “Angular 2 quickstart” using Visual Studio. With this you can setup and run Angular 2 quickstart in Visual Studio 2017. Please refer to the official Angular 2 Quickstart. This Visual Studio adaption of the Angular 2 Quickstart can be found on my GitHub site.


Here are the step by step details on how to setup Angular 2 project in Visual Studio.
·         Let’s start by creating a new ASP.NET Core project in Visual Studio

·         Use Empty template to create a blank solution

·         Using Nuget install MVC

·         After installing MVC, install static files middleware. This middleware is needed to serve javascript and html pages

·         Build the project to ensure all the dependencies are downloaded

·         Add MVC services in ConfigureServices method in Startup.cs
    services.AddMvc();

·         After that, in Configure method configure Angular 2 startup and MVC (replace the app.Run code)
// to serve index.html as the default page
app.UseDefaultFiles();
// to serve all the javascript, css and other static pages
app.UseStaticFiles();

// configure route for webapi
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller}/{action}/{id?}");
});

·         To download all the Angular dependencies using npm add package.json under wwwroot

·         From Angular 2 Quickstart GitHub copy the package.json. In this blog unit testing is not covered. Hence there is no need to include devDependenies. Here is the complete code for package.json

{
  "name": "angular-quickstart",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",
  "keywords": [],
  "author": "Prasanna Kumar Pattam",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",

    "angular-in-memory-web-api": "~0.2.2",
    "systemjs": "0.19.40",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.1",
    "zone.js": "^0.7.4"
  },
  "repository": {}
}

·        Wait for the packages to be downloaded
·         From Angular 2 Quickstart GitHub copy the following files/folder to the wwwroot folder
o   index.html
o   systemjs.config.js
o   styles.css
o   favicon.ico
o   tsconfig.json
o   app\main.ts
o   app\app.module.ts
o   app\app.component.ts
·         Once you copy the above files, the solution explorer for wwwroot should look like this

·         Build the solution so that javascript files are generated for the typescript files
·         If you get compile error, delete tsconfig.json files under node_modules (not the one we copied). We don’t need to compile the node_modules
·         Once you successfully compiled, run the application.



Voila our first Angular 2 app running in Visual Studio 2017. 

Git, Node and NPM for Windows

Here are bunch of resources if you want to run Git, Node and NPM in Windows.

Git

Git is included in VS 2013. For earlier versions you need to install the Visual Studio Tools for Git. This can be downloaded and installed from


Visual Studio does not set GIT to the windows path variable as a result you cannot use the Git from regular command prompt. You can use Git from VS command prompt. To set the path element, please refer to


After these two steps you can run Git from command prompt

Node and NPM

Download and install the 32 bit or 64 bit windows installer from the NodeJS website


This automatically sets up the Node and NPM. You can directly use it from command prompt

Monday, April 20, 2015

AngularJS renamed to Angular

I believe AngularJS team officially renamed themselves as Angular. They dropped the JS from its name. It seems that they are differentiating between 1.x and 2.0 with the name suffix. That is AngularJS means 1.x and Angular means 2.0.


Earlier JS suffix is used to differentiate between Angular javascript framework and physics angular. As AngularJS became so popular that searching for Angular on bing or google is mostly returning AngularJS hits. Hence there is no need for AngularJS to suffix itself with JS. May be now the Angular Physics should suffix itself J

Saturday, April 18, 2015

MVC 6 Project from Scratch

As you know MVC 6 has significant changes from its previous version. Sometimes you won’t feel these changes when you use the predefined Visual Studio templates. If you want to know the bootstrapping changes in MVC 6 the easiest one would be start the Visual Studio project with empty template and keep adding those you need.

In this blog I will go through the steps involved in creating a MVC project using an empty template. I will add all the necessary elements to this empty template and make my project runnable.
Here I am using the Visual Studio 2015 CTP 6. As it is a CTP version, the actual steps may change in the RTM.

First start off creating a blank ASP.NET project with Visual Studio 2015 CTP 6. As shown in the image below pick the web template and choose ASP.NET Web Application.




In the next screen select "ASP.NET 5 Preview Empty” template and click ok. This will create the blank ASP.NET web application.




Once the empty project is created, take a look at the Solution Explorer (as shown below).



As you notice there are significant differences. Below are the brief description of some of the changes in MVC 6 compared to previous versions:


  • You may not notice but there is no project file. All files in the folder will be automatically picked up. “project.json” contains the configuration for the project
  • There is no web.config. MVC 6 introduces configuration through Json file. I will cover this in my next bolg
  • There is no Global.asax file. This was replaced by Startup.cs which is used to configure the web application.
  • Wwwroot folder was introduced. This is similar to the Content folder in the previous version. This is used for storing all the static content of the application. When referencing from your view you don’t need to specify “wwwroot”
  • Under References you will observe two refernce folders “ASP.NET 5.0” & “ASP.NET Core 5.0”. In addtion to deployment as earlier, ASP.NET can also be deployed side by side or in other environments. This is sometimes called as cloud deployment.

As mentioned earlier Startup.cs is used to configure our web application. Here is the code generated by Visual Studio for Startup.cs.

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
        }

        public void Configure(IApplicationBuilder app)
        {
        }

    }

As you see this is no code. When the application starts, ASP.NET calls ConfigureServices where we would configure MVC and any other services. After this ASP.NET invokes Configure method, in which we can configure the services that are added to ASP.NET.

Let’s start MVC by adding MVC 6 to our project using Nuget as shown below:



Once Nuget successfully install MVC 6, update the Startup class with the below code, where we add MVC service and configure the routing.

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });
            });
        }

    }

Once MVC service is added, rest of this is similar to what we do in earlier versions of MVC. So let’s add a Controller. For this we first need to create the Controllers folder and followed by creating a Controller class as shown below.







Here is the default code in the controller that is generated by Visual Studio

    public class HomeController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

    }

Now Similarly create the View for the Index action (first creating the Views Folder)




Once the view is created, let's add the "Welcome to MVC 6" message into the view as shown below

@*
    For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    // ViewBag.Title = "Home Page";
}

Welcome to MVC 6

We are done with our code. Now let’s run the application and we can see our message.




So we were able to create an MVC application using a blank Visual Studio template. In my next blog I will show how we can create a WebAPI using MVC 6 controller.

I uploaded my code on to my GitHub.

Sunday, April 5, 2015

Watching multiple $scope attributes using $watchGroup

We all know that $scope.$watch() provides a mechanism to observe changes on a particular attribute or expression and allows us to handle the changes by registering to the callback event. A good example of using this is to calculate the elapsed date (date difference) between a user entered date and today’s date. In my scenario there is a datepicker where the user picks a date and I have to show the date difference between that date and current date. So I added watch on the user picked date and in that $watch callback I calculated the difference using my DateDiff routine as shown below

$scope.$watch('vm.model.ExamDate, function (newValue, oldValue) {
    var diff = utility.dateDiff(newValue, todayDate);
    //rest of my code
});

After this I had to extend my datediff routine to show the difference between two user entered dates, in this scenario I have to show difference between the ExamDate and DateOfBirth. For this exact purpose AngularJS introduced the watchGroup which can be used to observe changes in multiple variables and accordingly run the code. Here is my code using watchGroup to observe changes in ExamDate and DateOfBirth and whenever either one changed I am calculating the difference between these two dates. Here is my code for this:

$scope.$watchGroup(['vm.model.ExamDate', 'vm.model.DOB'], function (newValues, oldValues, scope) {
    var diff = utility.dateDiff(newValues[1], newValues[0]);
});

So as you see $watchGroup provides the capability of wating multiple $scope attributes.
Finally AngularJS also has $watchCollection which is used to watch changes to the properties of an object and fire the change event.