Monday, July 23, 2018

AngularJS vs Angular: index.html and boostrapping

This is part of a series that compares AngularJS (the old Angular) to Angular.

For the first comparison, I’m going to look at index.html and how the apps are set up or bootstrapped.

AngularJS

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html ng-app="mainModule">
<head>
  <title>TasksA1</title>
  <script src="https://code.angularjs.org/1.7.0/angular.min.js"></script>
  <script src="https://code.angularjs.org/1.7.0/angular-resource.min.js"></script>
  <script src="https://code.angularjs.org/1.7.0/angular-route.js"></script>
  <script src="app.js"></script>  
  <script src="app-routing.module.js"></script>
  <script src="services/todo.service.js"></script>
  <script src="pages/home/home.component.js"></script>
  <script src="pages/to-do-list/to-do-list.component.js"></script>
  <script src="pages/to-do-item/to-do-item.component.js"></script>
  <!-- Angular CLR project somehow adds Boostrap into the file -->
  <link rel="stylesheet" 
  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" 
  integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" 
  crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <h1>ToDos using AngularJS (1)</h1>
  <a href="#!/toDoList">ToDos</a>
  |
  <a href="#!/toDoAdd">New ToDo</a>
  <div ng-view></div>
</body>
</html>
index.html

On line 2, there is the ng-app directive, telling AngularJS to do its magic. Lines 5-13 there are script tags, first Angulars then mine. Then on line 26 we have a div with a ng-view directive, that's where all the magic happens.

Angluar

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>TasksA6Ts</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <h1>ToDos using Angular /w TypeScript</h1>
  <a href="/toDoList">ToDos</a>
  |
  <a href="/toDoAdd">New ToDo</a>
  <app-root></app-root>
</body>
</html>
index.html

The app-root tag replaces the div with the ng-view directive. There is no ng-app directive or script tags. When I did a view source. But how does it know which files to insert; I think it gets them from app.module.ts (the files are reduced to ES5 and dumped into a single file).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { ReactiveFormsModule , FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { ToDoItemComponent } from './pages/to-do-item/to-do-item.component';
import { ToDoListComponent } from './pages/to-do-list/to-do-list.component';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { HomeComponent } from './pages/home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    ToDoItemComponent,
    ToDoListComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
app.module.ts

These are the files in the actual project, but an Angular app needs to be built. I built the app with the command ng build and when I look at the build results and this is the generated index.html:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>TasksA6Ts</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <h1>ToDos using Angular /w TypeScript</h1>
  <a href="/toDoList">ToDos</a>
  |
  <a href="/toDoAdd">New ToDo</a>
  <app-root></app-root>
<script type="text/javascript" src="runtime.js"></script>
<script type="text/javascript" src="polyfills.js"></script>
<script type="text/javascript" src="styles.js"></script>
<script type="text/javascript" src="vendor.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Generated index.html

All of the TypeScript files mentioned in app.module.ts are transpiled into ES5 into main.js

About the series AngularJS vs Angular


AngularJS vs Angular: The Introduction

As I try to maintain my status as a “Full Stack Developer” I have been looking at Angular and AngularJS. So, what gives? Angular is an open source web application platform that Google released in 2016 to replace AngularJS (then called Angular). AngularJS is Google’s original Angular, released in 2010. Angular and AngularJS are completely different.

In this experiment I wrote a simple list/detail site in both AngularJS (in JavaScript ES5) and Angular (in TypeScript). I created a simple REST endpoint with JSON-Server.

Methodology

AngularJS

I took a project I wrote a coupe of years ago and simplified it and then refactored it to match the files structure of the Angular app (foo.ts became foo.js).

Angular

I created the app, the components and services using the Angular CLI (version 6). I put all of the REST calls in a “services” to match the architecture I used in the AngularJS app; most of the samples I found online called the http methods directly from the components.

The App

The Task List is the “Hello World” of databinding, so I went with this. I dropped the “People” table so we only have 1 table: “Todos”. Both apps do the same thing using the same structure as far as I could push it.

About the series AngularJS vs Angular

Thursday, June 28, 2018

ACID Cheat Sheet

This on is for Database Transactions

  • Atomicity – The transaction is all or nothing. Succeeds or fails as a unit.
    If the bank adds $100 to my account, then the $100 must come from your account.
  • Consistency – Outside of the transaction, we can only see the begin or end state of the transaction.
    We will never see the half of the transaction where I get the $100 and you haven’t given up your $100. (too bad).
  • Isolation – The transaction is hidden from the outside world until it is committed.
    I imagine that during a transaction there are two universes. In the transaction’s universe, the values change as you work though the steps. In the other universe, the values remain as they were before.
  • Durability – Once the transaction is committed, it is on the record forever.
    If they decide that I shouldn’t have gotten the $100 from you after the transaction was committed, they can create a new transaction where they take the $100 away from me, but they can’t reverse the committed transaction. You can’t rewrite history.

Tuesday, May 29, 2018

4 Pillars of Object Oriented Programming Cheat Sheet

Another cheat sheet for interviewing.
I think of the 4 pillars consisting of 2 coins. Abstraction / Encapsulation and Inheritance / Polymorphism. So here they are:
  • Abstraction – Look at the thing we are modeling: What is it? What are its characteristics? What does it do? Make the object as simple as possible and don't include unnecessary functionality. Data Hiding for simplification.
  • Encapsulation – Create a black box around the how. You interact with an object through public properties (setters and getters) and methods. Data Hiding for security.
Both Abstraction and Encapsulation are about all about hiding stuff from us. Protecting us from unnecessary complexity. Abstraction takes place when we fill out our CRC cards when we are designing our classes and Encapsulation takes place when we actually write the code.

  • Inheritance – Reuse code! A child class inherits from a parent, from a grandparent, from great grandparent, and so on .. I think of examples of class hierarchies, like Animal, Dog, Pitbull, etc.
  • Polymorphism – From "many forms": A child can be substituted for the parent. If you cast a Pitbull as a Dog, you can call the Dog.Bark() method and the Pitbull.Bark() will be run (if it has been overridden). Also, you can have a collection of Dogs, and issue the Bark() command on each of them without caring which kind of Dog is barking (Pitbull or Corgi).
I think of Inheritance and Polymorphism as cause and effect. Because a Pitbull is derived from Dog (Inheritance), the Pitbull can bark like a Dog (Polymorphism).

Friday, May 25, 2018

S.O.L.I.D. Principals Cheat Sheet


I am between gigs, so I have been given opportunities to discus the SOLID Principals along with others of the classics of Object Orientation and basic Computer Science.

The SOLID Principals are somehow connected to Robert C. “Uncle Bob” Martin and his 2000 paper Design Principles and Design Patterns. The word “Solid” appears nowhere in the document. Well anyway, the SOLID Principals are:

  • Single Responsibility Principle – A class should do one thing and do it well. No more epic methods or “manager” classed that do everything.
  • Open/Closed Principle – Open for extension but closed for modification. When you publish an API, others are depending on you. Don’t change the way that a method works. Someone may even be depending on a bug in your code!
  • Liskov Substitution Principle – You should be able to substitute a child for a parent and everything work. Named after Barbra Liskov of MIT; learning this kind of detail makes it easier for me to remember.
  • Interface Segregation Principle – More smaller interfaces! Each interface should do 1 thing. Avoid creating a monster interface that does everything. (this is an extension of the Single Responsibility Principal, right?)
  • Dependency Inversion – Don’t create an object directly. Use an abstraction to create it. Whether it is the Abstract Factory pattern, an IOC container, simply pass in the object in, or whatever.

Wednesday, August 02, 2017

CSS Popup Sample

Here's some code I wrote for something I'm doing for work.
This code will show and hide a popup
<html>
  <head>
    <style>
      #pop {
          height: 200px;
          width: 200px;
          position: fixed;
          bottom: 50%;
          right: 50%;
          border: 2px solid;
          padding: 10px;
          background: white;
          display: none;
        }
        #buttonsOnPop {
          position: absolute; 
          right: 0; 
          bottom: 0;
          margin: 5px;
        }
        #popTitle {
          vertical-align: top;
          text-align: center;
          width: 100%;
          background-color: limegreen;
        }
      </style>
      <script>
        function closePopYes() {
          alert("yes");
        }
        function closePopNo() {
            document.getElementById("pop").style.display='none';
        }
        function showPop() {
          var text = "<p>To be or not to be</p><p>Revente</p>";
          var popContent = document.getElementById("popContent");
          popContent.innerHTML = text;
            document.getElementById("pop").style.display='block';
        }
     </script>
  </head>
  <body>
    <div id="pop">
      <div id="popTitle">Pop Window</div>
        <div id="popContent">
      </div>
      <div id="buttonsOnPop">
        <button id="yes" onclick="closePopYes();">Yes</button>
        <button id="no" onclick="closePopNo();">No</button>
      </div>
    </div>
    <button id="showPop" onclick="showPop()">Show Pop</button>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur vitae iaculis enim. 
Vivamus a tellus sit amet tortor mattis auctor at eget purus. Fusce condimentum semper 
varius. Integer ultricies enim et ipsum scelerisque, dignissim ultricies metus molestie. 
Quisque rutrum, sem id vehicula malesuada, orci purus malesuada dolor, id vehicula nulla 
nisi sed dui. Donec at eros vestibulum, euismod mi quis, rhoncus justo. Curabitur quis 
metus sit amet erat efficitur pellentesque. Nunc dui massa, efficitur ac dapibus ut, 
interdum vel metus. Nunc mattis eleifend nisl, id rhoncus erat cursus et. Nullam semper, 
risus sed feugiat elementum, turpis lacus egestas nisi, quis bibendum lorem turpis eu 
purus. Etiam nec lorem tristique, condimentum ligula ac, mattis erat. Proin aliquet 
quis lectus eu hendrerit. Curabitur vitae laoreet nulla. Pellentesque imperdiet odio id 
urna imperdiet bibendum eget non erat.
</p>

  </body>
</html>

Thursday, June 30, 2016

VS Item Template for ASP.NET Identity 2.0

ASP.NET Identity does many cool things; a lot more than the old Membership Provider did. I did a project lately that needed to do what the Membership Provider did, Users and Roles. It turns out that the ASP.NET Identity supports Membership, but it is poorly documented.

I looked high and low on the Internet for good examples of ASP.NET Identity doing simple Membership without any extra fluff (my client didn’t want any of it), but did not find any! Since I could not find a good any, I decided to make one and put it on GitHub.

I also built a Visual Studio Item Template that will add most of what you need add and edit roles and users.

The Template

I released my template on my Github account here. It only works with ASP.NET MVC projects created in Visual Studio 2015. It is too stupid to validate that you are using To use my template:

  1. Download FormsAuth.zip from the latest release.
  2. Copy it to <My Documents>\Visual Studio 2015\Templates\Item Templates\Visual C#
  3. Open Developer Command Prompt for VS2015 as administrator
  4. Run devenv /installvstemplates
  5. Open Visual Studio 2015 (don’t use an already opened copy, the template won’t be there)
  6. Create a new project (you can open an existing project as long as it is an ASP.NET MVC project created in VS 2015 or upgraded to ASP.NET Identity 2, VS 2013 projects won’t work, then skip to step 9)
  7. Choose ASP.NET Web Application, name it and click OK
  8. Select the template MVC
  9. Project => Add New Item (or Ctrl+Shift+A)
  10. On the left, select Visual C# then select Forms Auth Role and User CRUD for MVC Project using ASP.NET Identity (better name?)
  11. Follow the instructions in the read me file.

The things I make you do

I wanted to be safe and not touch any of your code, so I am asking you to do it for me.

Create ApplicationRoleManager

The default Visual Studio ASP.NET MVC project is aware of Users but not Roles. You will need to tell it to care about Roels by adding an ApplicationRoleManager. So go to App_Start > Startup.Auth.cs and change the Startup.ConfigureAuth to look like this:

public partial class Startup
{
  
public void ConfigureAuth(IAppBuilder app)
   {
       app.CreatePerOwinContext(
ApplicationDbContext.Create);
      
// Add this line:
       app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
       app.CreatePerOwinContext<
ApplicationUserManager>(ApplicationUserManager.Create);
       app.CreatePerOwinContext<
ApplicationSignInManager>(ApplicationSignInManager.Create);

Add links to navigate to User and Roles pages

OK, you have Users and Roles and forms to edit Users and Roles; but how do you get to them? If you are using the default ASP.NET MVC layout, make the main menu in _Layout.cshtml look like this:

<div class="navbar-collapse collapse">
   <ul class="nav navbar-nav">
       <li>@Html.ActionLink("Home", "Index", "Home")</li>
       <li>@Html.ActionLink("About", "About", "Home")</li>
       <li>@Html.ActionLink("Contact", "Contact", "Home")</li>

       @if (Request.IsAuthenticated && User.IsInRole("Admin")) {
          
<li>@Html.ActionLink("RolesAdmin", "Index", "RolesAdmin")</li>
           <li>@Html.ActionLink("UsersAdmin", "Index", "UsersAdmin")</li>
       }
  
</ul>
   @Html.Partial("_LoginPartial")
</div>

Create “Seed” User

OK, you have all this wonderful User and Role functionality. The trouble is that you need a user who is in the role “Admin” to add and edit users. I added a special form that will allow you to register one and only one “seed” user who will be a member of “Admin”; if it sees that the role “Admin” already exists, it will send you to an error page. Go to http://yourdomain/seeduser/register and create a your new very first Admin user! After you create your seed user, you can delete SeedUserController and the SeedUser Views (files in /Views/SeedUsers).

Other things to do

If you don’t want to expose any of your site to the outside, make all controllers require authorization with the [Authorize] attribute.

Delete Register page and routes (Including my Register Seed User). In the AccountController, delete (or comment out) both Register methods.