This is part 5, the final installment of the series.

You can download all of final code off of my github page here

If you’ve missed any other section, I recommend you check those out also.

Part 1

Part 2

Part 3

Part 4

Here in the final part of this series we are going to bring everything together into a fully functional app. If you recall from the end of part 4, we discussed what files we would need to add to our app to complete it.
Here is that list again:

  1. app.component.ts and app.component.html
  2. dashboard.component.ts and dashboard.component.html
  3. todo-list.component.ts and todo-list.component.html
  4. todo.component.ts and todo.component.html
  5. todo.ts
  6. header.component.ts and header.component.html
  7. todo.service.ts

Here’s what our file system looks like now:

alt text

Im not going to get into each file in detail in this post. Ill briefly discuss the series of events that occurs then the app starts up but the best way to learn it is to download the code from my GitHub page and run it for yourself.

Here is a quick overview (I recommend opening each file as we go along):

  1. the index.html page is parsed by the browser
  2. When it hits line 38, it loads the app/main module – main.ts
  3. main.ts imports bootstrap from the angular library and AppComponent (app.component.ts) and then calls bootstrap(AppComponent) to start up the app
  4. app.component.ts: This is the real meat of the startup procedure. We have:
    1. A bunch of import statements to import ‘stuff’ (routing, http services, other components) that will provide functionality to the app.
    2. Our component MetaData section setting the selector and template. If we look at the template that is specified in the templateUrl: ‘app/app.component.html’, we have:

alt text

    in this template, you can see other custom tags where other components will be loaded. For instance, there is a "header-content" tag which is...well.....where the header content goes...=) as well as the "router-outlet" tag which defines where our pages will be loaded as we browse around the site.

3. A @routeConfig section to configure how routing will work and what the routes are (<a href="https://angular.io/docs/ts/latest/guide/router.html">read about routing here</a>)
4. An export statement so that this component is available to be imported into other components

As each of the imports are satified within the app.component.ts file, those imported components have dependencies and so on down the chain until all of the components are loaded and the page displays.

Again, I highly recommend that you take the time to download the code if this is unfamiliar to you and step thru it to get a clear understanding of how the process works. I always find that is the best way for me to learn something.

If you’re reading this, Im sure that you have probably read the Introductory docs that were put out by the Angular team, but if not, that is highly recommended as well.

Thanks for visiting and I hope this series has been helpful.

{ 0 comments }

This is part 4 of the series.

If you’ve missed any other section, I recommend you check those out before digging in here.

Part 1

Part 2

Part 3

The Angular Bits

OK, so we’ve spent the last 3 posts getting our site up and running and configuring the server site to support our new angular todo app but we haven’t started working with Angular yet. Now is the time.

Before we dig into the code, let just take a quick look at the finished app. Its a very simple app with 3 views.

  1. A dashboard view
  2. A list of todos
  3. A screen to create/edit todos

This is the dashboard

alt text

This is the list of todos

alt text

…and the edit/create todo screen

alt text

The example is a little contrived. I created the dashboard just to have another place to navigate to although in a real app the dashboard would likely serve a purpose. As you probably noticed, Im using bootstrap here to make the app look a little better.

OK, so now we know what it looks like, how do we get there?

Lets take a quick look at what we have in VS Code.

alt text

In this expanded view, you can see all of the files that we have created in parts 1, 2, and 3 of this series. So far, so good. But where on earth do we put the Angular parts?

The angular related stuff is going to live inside the wwwroot folder. What is that you ask? good question.

The web root of your app is the root location in your project from which HTTP requests are handled (for example handling of static file requests). When using the static files middleware only files from the web >root folder are accessible; the other files in the content root cannot be accessed remotely. The default web >root path is content root/wwwroot, but you can specify a different location using the WebHostBuilder.

You can read more from the docs here

Now that we know where to put the files, lets create some files and folders within the /wwwroot directory:

  1. create a folder named app
  2. create an index.html file
  3. in the app folder, create:
    • main.ts
    • app.component.ts
    • app.component.html

Lets take a look at our newly created files now. first up, Index.html

alt text

As you can see Im loading most of the libraries directly from the internet rather than locally. You can do whatever you like. The only ones Im working with locally are toastr and jquery. One item to take note of if you havent worked with ES2015 yet is the System.config and System.import stuff.

The config section is specifying that we are going to use typescript and the import stuff is required because when using ES2015 we put our code into modules and export and import those modules. you can read all about modules here

You can see our first import here on line 37 where the code is saying “load the main module from app/main.” That is the starting point for our app. Lets take a look at that file next.

alt text

This file looks pretty simple. If you remember from Angular 1, we put the “ng-app” attribute in our html to specify what made up our Angular app. That process was and still is called Bootstrapping, only now we do it in code and that is what we are looking at in this code sample.

First we are importing bootstrap from angular2/platform/browser – thats part of the core library from the team at google. Next, we import App.component. That component is created by the developer and its the true starting point for the application.

We just call bootstrap() passing it our AppComponent and the app will start up.

Now let take a look at app.component.ts

alt text

So here, we are importing Component from the Angular framework on line 2. On line 4, we have whats called a decorator that we are using to configure this component. Within this decorator, we are specifying the css selector, todo-app. If you jump back up to the index.html page, you can see on line 43 we have a tag by the same name. When this component loads, it will take the contents of its template and put it into the DOM where the css selector specifies.

We have a very simple template here. Its an inline template string. Note that we are using backticks “ to indicate the beginning and end of the template. With more elaborate templates, we will typically use an external file but this is a good way to do a sanity check that everything is working the way we want.

And finally, we have to export this class to make it available for import elsewhere and that is exactly what we are doing on line 11.

So with all of those bits in place, we can jump out to a command prompt and enter the command dotnet run which will fire up our web server. Once it up and running, browser to http://localhost:5000/index.html and you should see you newly created Angular2 app running it all its glory.

alt text

Just for fun, lets add a text string that we will bind in our template.

alt text

alt text

The binding we’re using here is the same as it was in Angular 1.

We’ll see this app.component.ts file change quite a bit as we work thru this example.

With those few bits in place, we have a skeleton to hang the rest of our app on. Currently, our app.component has an inline template but as we progress Ill move that html out into a file called app.component.html.

Notice how app.component.ts and app.component.html are named the same? That isnt a mistake, by all means its very intentional. Naming our files in this way makes it super easy to find what template goes with what Component.

Armed with this knowledge, if we think about the screens we looked at above, I can envision needing the following files:

  1. app.component.ts and app.component.html
  2. dashboard.component.ts and dashboard.component.html
  3. todo-list.component.ts and todo-list.component.html
  4. todo.component.ts and todo.component.html
  5. todo.ts
  6. header.component.ts and header.component.html
  7. todo.service.ts

You can read more about how to define your files in The Angular 2 Style Guide

And with that Im going to call it a wrap on Part 4.

To quickly recap, we now have the server and the client plumbing in place and can being building our app in earnest. We also outlined what files we think we’re going to need based on the screen shots of the app.

In the next post, we going to code up the files we just defined and keep moving forward.

Thanks for visiting.

{ 0 comments }

Welcome back!

This is part 3 in this series Ive appropriately named:

Creating a simple Todo list with Angular2 and asp.net core

If you’ve arrived at this page prior to reading part 1 & 2, you can check them out here:

Part 1

Part 2

Coding up the controller

We left off in part 2 having just created a vanilla controller. Im going to replace all of that boiler plate code with an implementation that access our database and provide full CRUD capabilities. Here is that new code:

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using SimpleTodo.Models;

namespace SimpleTodo.Controllers
{
    [Route("api/[controller]")]
    public class TodoController : Controller
    {
        
        ITodoRepository _TodoItems;

        //you can see here in the controller constructor that the TodoRepository is being 
        //injected for us by the DI Container - we set that up in Part 2 of this series
        public TodoController(ITodoRepository todoItems)
        {
            _TodoItems = todoItems;
        }
        
        // GET api/todo
        [HttpGet]
        public IEnumerable Get()
        {
            return _TodoItems.GetAll();
        }

        // GET api/todo/5
        [HttpGet("{id}")]
        public IActionResult Get(string id)
        {
            var item = _TodoItems.Get(Convert.ToInt32(id));
            if(item == null)
            {
                return NotFound();
            }
            return new ObjectResult(item);
        }

        // POST api/todo
        [HttpPost]
        public IActionResult Post([FromBody]TodoItem todo)
        {
            if(todo == null)
            {
                return BadRequest();
            }
            _TodoItems.Add(todo);
            return new NoContentResult();
        }

        // PUT api/todo/5
        [HttpPut("{todoId}")]
        public IActionResult Put(string id, [FromBody]TodoItem item)
        {
            if(item == null)
            {
                return BadRequest();
            }
            _TodoItems.UpdateTodo(item);
            return new NoContentResult();
        }

        // DELETE api/todo/5
        [HttpDelete("{todoId}")]
        public void Delete(string todoId)
        {
            _TodoItems.DeleteTodo(todoId);
        }
    }
}

Now that we have the controller coded up and in place, lets build and run the site and browse to it in chrome

alt text

NOTE: if you are following along with this series and building it as you go, you will have to kill your server and restart it each time you make changes to the server side code in order to see your changes reflected.

when we navigate to http://localhost/api/todo what do we see!!! Drum roll please…..

alt text

…and we get an empty array. Not all that exciting but it makes perfect sense. We dont have any records in the database yet. Lets use Postman to create a record as a quick test.

Using Postman

If you dont know, Postman is an extension for Chrome. You can get it by going to http://www.getpostman.com or when you’re in Chrome, click on the Hamburger icon -> More tools -> Extensions and search for Postman.

alt text

Once you have it installed, you can launch it like any other app.

Using the Postman builder, I set the method to POST, the address to http://localhost:5000/api/todo, in the Headers section I add Content-Type – application/json and finally in the Body tab, I entered the following JSON:

{name: "my first todo", isComplete: false}

with all that in place, I click the Send button and get a “204 – No Content” Response.

At first glance, that may feel wrong but if we look at the code for the POST action in our TodoController we can see that it return a NoContentResult() so we know all is good with the world.

// POST api/todo
        [HttpPost]
        public IActionResult Post([FromBody]TodoItem todo)
        {
            if(todo == null)
            {
                return BadRequest();
            }
            _TodoItems.Add(todo);
            return new NoContentResult();
        }

Now, if we open up the browser again, we can see our newly created record being served from the Database. Happy days!

alt text

Our server side setup and coding is now complete. In the next post, we are going to turn our attention to the client side of this application and actually start implementing the “Angular” part.

Until next time….Thanks for visiting.

{ 0 comments }

If you recall from part 1, we finished creating the site using Yeoman and viewed our new creation in the browser.

Before we get started on the Angular2 bits, we need to do a little coding and configuration on the server side. Lets look at that now.

The Database

The database on the backend of this app is going to be Sqlite. Im going to connect to it using Entity Framework. In order to use EF, I need to reference the correct libraries in my project.json file. Lets add those dependencies now:

alt text

Once Ive added the references to my project.json file, I jump out to the command prompt to run “dotnet restore” again to be sure I have all the required bits.

alt text

Now that we have EF in place, lets turn our attention to the todos.

Thinking about what we’re building

It will probably benefit us greatly to stop and think a moment about what we are building. As the title implies, we are building a simple todo list but what makes up a todo? Well, for the purposes of this post, we are going to keep it simple.

A todo is made up of the following properties?

  1. An id
  2. a Name
  3. a boolean flag indicating if the todo is complete

Let create that simple class now. Looking at VS Code and what Yeoman created for us, where should we put this class?

alt text

A Models folder was not created for us, so Ill go ahead and add that Models folder now. Now we need to create the class for TodoItem.cs. We could just create a new empty file but we can use Yeoman again here to make our lives a bit easier.

At the command prompt Ill type “yo aspnet –help” to get a full list of all the commands yeoman knows about for the aspnet generator.

alt text

You can see all the subgenerators that this aspnet generators provides. So, If I want to create a Model class I can use the yo aspnet:Class generator and yeoman will create the class for me. Another good time saver. Ill just navigate to the Models folder and run the command.

alt text

Ill edit the newly created file to include the using statments for Entity Framework and the annotations that will be used by the migration to create the table and columns in the db.

alt text

Next up, the Repository

With our simple model in place, let create the Repository. We will be handling simple CRUD operations with this app so the interface is pretty straight forward. Ill use Yeoman again to create these files.

alt text

The last file that I created above is the TodoContext. This is a simple file that EF uses when interacting with the database. You can read more about working with DbContext here

alt text

alt text

The code for the Repository implementation gets a little long to display here so check it out on github if you’re interested.

With our model and repository now in place, we can create the migration we need and configure the Startup.cs file to load our repository into the DI Container. Lets configure the Startup.cs file first.

alt text

If you notice my fancy arrows above, you can see that I appended the AddJsonOptions() method call and setup the contract serializer. This will make sure that we have camel case property names on the client side while using Pascal cased names on the server.

The second arrow is registering our ITodoRepository with the DI Container. Essentially, what this says is “when someone asks for an ITodoRepository, give them a TodoRespository”…. Easy Peasy!

Now lets create and run those EF migrations.

alt text

You can read more about the EF Command line tools here but what I’ve done here is pretty straight forward. I created a new migration called “TodoList” and then applied that Migration to the Database. Any Ruby on Rails developers out there should feel very at home with this method as its pretty much exactly the same as rails.

With that complete, we can check to see if our database was created in VS Code.

alt text

You can see our newly created todo.db in the bin folder and all of the files we created above in the Models folder.

OK, so whats next? We have our database and table to hold data and we have a repository to access that data. Now we need to turn our attention to the Controller. The controller will provide the API that the Angular app will make calls to in order to get/post/put and delete data. The yeoman generator did create a controller for us called HomeController. Lets look at that:

alt text

Looking at this controller, we can see that it wont do. This controller is setup to return views but we want to access an API for data only. Microsoft had something in the past called Web API that did just that but Web API is now baked into the same framework as the regular Controllers. All Controllers now inherit from the Controller base class regardless of type.

So what to do? Yeoman to the rescue again.

Remember that long list of Subgenerators that we looked at at the beginning of this post? No? go take a look, Ill wait…………..if you look at the bottom of that list you’ll see there is a sub generator for WebAPIController. Great news…..lets use that!

Ill just navigate to my Controller folder and…..

alt text

and it gives us exactly what we need.

alt text

With our new controller in place, we can fire up the site and browse to http://localhost:5000/api/todo and we should get back an array with 2 values just as shown in the Get() method in the controller.

With the controller in place, Ill call this post a wrap.

In the next post we will finish our work on the server side by:

  1. Setting up the controller to access the database
  2. Test the API via a browser as well as do a quick test using Postman

Once that’s all working correctly, we can turn our attention to the client side and the Angular bits.

Until next time…. Thanks for visiting.

{ 0 comments }

In the next few posts Im going to create a simple todo list using asp.net core and Angular2. Ill be developing on a mac but most of the stuff can be done on windows as well.

You can get all the source from my github page.

To get started, lets create the new asp.net app. I did this using Yeoman. if you don’t have yeoman on your system, you should check it out. It is essentially the “File | New Project” dialog when you’re working on a mac. Its a sweet time saver.

I simply navigated to the directory where I wanted the app to live and entered the magic “yo” command….

alt text

I selected the “Web Application Basic” option, answered a couple more questions and yeoman spit out it response.

alt text

You can see that it scaffolded out the app nicely and ran “npm install” and “bower install” for me.

at the end of the output you’ll see the following:

alt text

Seems simple enough – but what is this “dotnet restore” command?

Before we answer that, lets take a look at what the yeoman generator created for us. Im using Visual Studio Code which is a pretty sweet tool once you get comfortable with it.

alt text

If you’ve worked with other project in Visual Studio before, this should look pretty familiar. You can see in the file listing that there is a project.json file. In the current version of .NET core, the dependencies for each project are defined in this project.json file. I suspect this is going to change in future releases based on some Podcasts that Ive heard.

Here is a quick look at it.

alt text

So, to answer the question, what is this “dotnet restore” command. It essentially, parses this project.json file and goes out to nuget to satisfy the dependencies for the project defined in this file.

What else can this “dotnet” command do?

alt text

ok, so now lets run the “dotnet restore” command and get the libraries we need.

alt text

Now we can just run “dotnet run” and it compiles and fires up the site for us.

alt text

so if we navigate to http://localhost:5000, we see our newly created asp.net web app!!

alt text

That was easy!!

So thats all for this post. Lets quickly review what we did:

  1. created a new asp.net basic web application using yeoman
  2. Opened the newly created site in Visual Studio Code
  3. Looked at the project.json file – this file defines the dependencies for the application
  4. Looked at the “dotnet” commands – specifically the “dotnet restore” command and ran it. It reads the project.json file and downloads all of the dependencies for the project from NuGet
  5. After “dotnet restore” completed, we executed “dotnet run” which built and ran the site
  6. We navigated to our newly created, stunning site running at localhost:5000
  7. We sat back and looked dreamily at our new site and considered all the money it would make us…..well…maybe not that.

In the next post in this series, we are going to look at configuring the server side of the application by:

  1. Define our model classes
  2. Define and creating the Interface and classes required to interact with the database – in other words, our repository pattern
  3. Configure the site to use Entity Framework
  4. Use the Entity Framework Command Line tools to generate a migration and execute the migration
  5. Edit the Startup.cs file so we register our Repository with the Dependency Injection Framework that is built into .net core.
  6. Set the configuration so that we have camel casing on the client side for our JavaScript and Pascal casing on the server side.

I think that will be enough to cover in part 2 – stay tuned

Thanks for visiting

{ 0 comments }

Angle brackets guy builds a game for Windows 8

by Alex April 19, 2013

A little background It’s safe to say that my career has been primarily focused on the web. From “webmaster” in 1995 to the Chief Technology Officer position at a .com to more recent gigs in software development consulting, much of the software I’ve been involved in building has been web focused. I had taken a […]

0 comments Read the full article →

The Flavors of JavaScript Function Invocation

by Alex April 15, 2013

For those who may not be in the know, Functions in JavaScript are really very cool. They’re first class objects. What does that mean? It means that  JavaScript functions can have properties and methods just like other objects. Yes, you read that correctly, JavaScript functions can have their own properties and methods. In fact, Functions […]

0 comments Read the full article →

JavaScript–The Revealing Module Pattern

by Alex April 15, 2013

Working as a consultant, I get to see a lot of code written by different people. One of the things that consistently surprises me is how much JavaScript I still see written inside html pages. Haven’t we reached a level of maturity on the web where we as developers understand that there are essentially 3 […]

0 comments Read the full article →

Windows Phone – developing a more real-world app

by Alex March 1, 2012

OK, so in the last series of posts that I did I built a really simple windows phone app. That was a good opportunity for me to get comfortable developing for the phone, work with the tools a little and get a feel for working with the phone but lets be honest; The app was […]

0 comments Read the full article →

Read and Write ObservableCollection<T> to IsolatedStorage

by Alex March 1, 2012

How do I read and write my ObservableCollection<T> to IsolatedStorage? This is a question that I see posted over and over. In an effort to make the answer easy to find, here is a simple generic helper class that I use. public class IsoStoreHelper { private static IsolatedStorageFile _isoStore; public static IsolatedStorageFile IsoStore { get […]

0 comments Read the full article →