Tuesday, October 31, 2017

October Queso

  1. IBM Blockchain is a digital ledger (database) for an accounting history of transactions. Bitcoin transactions are managed this way.
  2. Vevo is some sort of video-for-the-web website full of music videos.
  3. clickbait is stuff that draws your eye online and tries to get you to click upon it thusly
  4. The build apparatus for Angular 4, in contrast to that of Angular 2 will do some tree shaking of what it builds and not loop in walled-off, unused code.
  5. Reshma Saujani is the creator of Girls Who Code. I saw a CNN.com interview with her in which she drops the name Wag! as the name of a dog-walking app, but more interestingly this interview suggests there are 500,000 open computer science jobs (USA) and 215,000 to 40,000 grads a year (USA) to fill the jobs. Me and my little Associates degree in computer graphics thus get a seat at the table amid the drought. Ha!
  6. Chart.js is... something to do with charts.
  7. Breeze.js apparently lets you do the LINQesque stuff you might do with underscore and also has things like validations and triggers.
  8. EpiServer CMS is a CMS (content management system).
  9. A subreddit is like a categorization or channel on reddit such as: "Today I Learned"
  10. Paintbrush is to Windows 3.1 what Paint is to modern Windows.
  11. staff aug (short for staff augmentation) is the consulting business model of putting butts in seats in a client's cube farm somewhere and little more than that, i.e. (short for id est) no real consulting
  12. PvP is Player vs Player in gaming, a term for fighting or at least messing with other human beings through avatars in game in lieu of just dueling "the computer" so to speak.
  13. Azure Notification Hub is for mobile push notifications.
  14. Big Design Up Front (BDUF) is a Waterfall thing.
  15. Zsh is both a shell and a scripting language.
  16. Blue Coat is owned by Symantec and provides some sort of cybersecurity.
  17. I have learned that with Entity Framework there is a schematics feature that will allow you to create CRUD logic from classes to MVC views, all wired-up, around a given database table. Also, there is a templating system for this stuff so that you may doctor-up the default barf into your own desired shapes in an easy-to-repeat way without you constantly manually doctoring-up what is rendered.
  18. To get rid of your Instagram account click on the icon that looks like a person (head and shoulders) at the upperleft (assuming you're at a laptop, not a phone) and then click "Edit Profile" and finally "Temporarily disable my account" and, yes, this will ask you for your password. If you created the account off of your Facebook specs you will need to go through the process of botching a manual login and resetting the password that way to satisfy this condition.
  19. JRPG stands for Japanese role-playing game.
  20. Gradle is yet another build tool.
  21. Alienware is yet another variety of laptop. These are geared for gaming.
  22. The SAS programming language is for statistical analysis. R would be the open source alternative for this language.
  23. Waffle is a project management solution.
  24. f.lux adjusts the "color temperature" of your monitor's display. Instead of showing blue light that your brain reads as "The sun is up." it will show more red light towards a day's end to help your brain get ready to go to bed, etc.
  25. FluentValidation by Jeremy Skinner is a C# validations framework.
  26. Middleman is a website framework for AS/400.
  27. Selenese is the language of Selenium for finding controls in HTML, etc.
  28. Yak shaving is performing small inane tasks over and over again when writing code. Yay!
  29. OpenCL or Open Computing Language uses the CPUs on different platforms for parallel programming.
  30. How many angels may dance on the head of a pin? As many as want to? Maybe not. Moore's law, named for a Gordon Moore, suggests the number of transistors that may fit on the head of a pin (integrated circuits for electronics) is ever growing greater over time. However, there is going to be a point where we as human beings cannot make stuff any smaller. The old Steve Martin joke about being too small resurfaces and at this point how do we advance tech? The cap should be reached just a handful of years away. Maybe everyone who hates to learn can just stop learning soon.
  31. There is something called an AdWalker for android phones which tried to hide ads in apps. It would walk all of your apps and doctor their aesthetics. In order to install it you had to be able to have admin access to your phone and that meant you would root your phone which took a flash/reflash of the firmware. The AdWalker is probably a bit out of date at this point.
  32. Slack has bought Screenhero and allows (inside of Slack now) for one to share their screen in a GoToMeeting fashion, however, better than GoToMeeting, there is no handing of controls back and forth to work. Instead both parties, or even as many as fifteen parties, may all use their mice at once. Your name just appears by your mouse at the displays of others. I thought of that old SubSpace game from the 1990s. As I recall, as you flew about your handle would float there by your spaceship or maybe it was how many points you were worth to kill. I can't remember. You would have a label by your icon. The Screenhero stuff is one of the not-for-free features of Slack. Message retention beyond a cap of ten thousand is another.
  33. Jeff Bezos, CEO of Amazon, is now the world's richest person and not Bill Gates.
  34. If a retailer makes its clientele swipe cards in lieu of using "the chip" then the realtor is liable for eating the cost of the purchase in the event of a fraud claim and not the credit card company itself as had been the case before the chip and is the case now with the chip.

Singleton pattern in Angular 4 apps?

I don't want to go to the database every time I display a dropdown list full of app administrators when the names in that list change so infrequently. I thus need to store some state on an object so that I may only call out to the database once, store the state, and then see the dropdown list for a second time in my wanderings of the app without going to the database a second time. Alright, to facilitate this, a coworker has made a model (TypeScript class) for holding singleton gunk and he loops it (an instance of the class) in at the constructor signatures of components. How does he keep the state when a new component is reached or the route is changed breaking with a strict SPA approach? What stops one controller from stepping on top of another and newing up a new singleton state object? If the outermost module loops in the singleton model as a provider or perhaps as one of many singleton objects in an array of objects, then the model will not step on itself at different constructor signatures. Something behind the scenes keeps the singleton nature from being sabotaged. I haven't written the code myself. This is my understanding. Also, you don't want to have spaghetti gunk in all of your controllers to check to see if a property on the singleton state object is truthy or falsey before using it and if falsey, and ONLY then, hydrating it from the database before returning it. Instead you should make your own miniservices for these mechanics. They are dubbed "resolvers" in the app I am currently working on.

Monday, October 30, 2017

The Angular community needs Yarn and it needs it now.

This morning I tried to just install the default angular-cli project with:

ng new whatever

 
 

Perhaps one must first run:

npm install -g angular-cli

 
 

The errors I ended up fighting with when I ran tests included:

  1. Can not load "webpack"!
  2. karma.Server is not a constructor
  3. Missing 'angularCli.config' entry in Karma config

 
 

Did this just work out of the box at one point in time?

Mark Halpin gave the last talk I saw at AngularMix and it was on Electron.

Alright, Electron is not simple. There is a lot of custom Electron code to write to get it spiffy and that is disappointing in the same way writing custom code for Xamarin is, you know? Electron Forge Templates can help you get started with canned versions of some of the stuff you need to roll. Other things mentioned include that Native.js is for NativeScript and that Squirrel runs Electron apps in the background, behind the scenes, in lieu of overtly like a desktop app, should you need the Electron equivalent of a console app or a Windows service I suppose. I really enjoyed the AngularMix conference. It was fun.

I saw Sani Yusuf speak at the AngularMix on trying to mix six applications into one solution.

Spheres include mobile, traditional web apps, standard desktop apps, IoT, server-side stuff, TV apps, and proprietary devices (i.e. console games, airline entertainment, etc.). Hey, I guess that is seven things instead of six. The process to make something friendly everywhere across all spheres, and, yes, this is really ambitious, is to write some code that uses Cordova (formally PhoneGap), wrap that in Ionic, wrap that again in a PWA (progressive web app) framework, and push out an Electron version for the desktop stuff. This stuff has a bit of a way to go before the tech is really there. Ionic 4.0 will be platform agnostic and will allow for jQuery instead of Angular. In native apps (apps for a specific platform), the SDK helps you bridge all pitfalls, but in Sani's paradigm an application has a myriad of technologies within it. Think of all the random things in a node_modules folder after all. Beyond the big picture, other things said include: Stencil.js will generate Web Components (which are like CDK components that are not Angular-specific) and the speaker predicts that Web Components may eventually be of other frameworks like React. The Nigerian term for desktop is dextop and phablets, not necessarily a Nigerian term, are ridiculously large phones that approach the size of tablets. WebView is the part of the Android OS for rendering out web pages. You use Java and Kotlin to program in Android Studio in the Android space as you might use Swift and XCode in the iPhone space. Azenda something like Bluetooth. Untappd is a social media drinking game app. This may unfortunately empower you to drink alone while pretending to be social which is pretty dangerous. Sworkit lets you make workout videos for yourself to follow along with. In closing I want to give a recreation of a bunch of concentric circles which I will represent with rectangles because that is much easier in HTML. Below I am guessing that container refers to an Electron container. This is a smidge inconsistent with the explanation of things wrapping things that I give above, but both what is below and what is above come from the speaker.

Your
Code
Ionic
Angular
WebView
Container

I saw Steve Sanderson speak at the AngularMix.

I saw this talk with the CTO of the company I am presently with and one thing he said to me immediately afterwards was how it made him think of WCF web services. I think his analogy is strong. Remember how in the WCF XML pattern you could make a model at the web service itself, a POCO, a then the applications consuming the SOAP API could have it without having to make duplicate code on their end to duplicate the shape of the object? We don't really have that with REST do we? We are just used to making our own object for a packet to send. That doesn't seem strange when you are just interacting with an API, but what if you are both authoring an API and consuming it in an Angular app that you are using as the front end for a .NET Core project which has REST endpoints as it's "other" front end? Then you will find yourself writing duplicate objects in both C# and TypeScript. There is now (HTTP) State Transfer which is a service that may transfer state between the server and the client. Swashbuckle for Swagger adds some metadata to what is at a REST endpoint to make the object to be communicated from C# to TypeScript intelligible at the TypeScript side. You need to use HttpWithStateTransfer in lieu of the usual Http at an Angular app to get this stuff working. Anyways, this should alleviate some of maintainability pain of having two objects on two sides of a divide and having to remember to update each one whenever there is a change. Imagine if multiple Angular apps use a common API. Then things could get dicey indeed without such a solution. Other things said: ng eject as a command means that I don't want to use the Angular CLI anymore and that I want to go back to using Webpack. Netty, a Java-based server, is probably the fastest server but .NET Core is still really fast and should be thought of as a fast server. Obviously, what Microsoft really wanted was something faster than Node so Node has been the thing to beat, not Netty. The .NET Core SDK has React.js and Angular templates that may be spun up from the command line. The following is a new piece of middleware for pointing an Angular app to a dist folder.

app.UseSpa("/dist", configure: ()=>
{
   if(env.IsDevelopment())
   {
      app.UseAngularCliServer(sourcePath: "ClientApp");
   }
});

I saw a talk by Daniel Roth on .NET Core APIs at the AngularMix.

As of version 2 of .NET Core as of a month and change ago there is now an option for making an Angular 4 UI project for a solution in Visual Studio when spinning up a new app. This was the most interesting thing said during the talk. The canned Angular app is of Webpack and not the Angular CLI unfortunately, but an Angular CLI version should come shortly in the next release. app.UseDeveloperExceptionPage(); is the middleware means for allowing exceptions to surface in the red and yellow screen of death. However, red and yellow have been replaced with blue and grey.

Sunday, October 29, 2017

"My ally, the CLI" was a talk by Mike Brocchi at AngularMix.

ng new whatever --minimal is the command to set up a new minimal (used to be called: "bare bones") project, of the modern Angular CLI shape as suggested here. There, it's already awesome! By default we are following John Papa's style guide, but schematics will allow you to define your own templates for defaults for things like components and modules. The angular-devkit is where schematics live. Mike recommended "rubber ducking" which is the art of asking a rubber duck questions in the name of figuring out an issue.

I saw Brian Clark speak on Angular security at the AngularMix.

Alright, I have some good news. Angular is basically already just secure as it is. It should be resistant to malicious input and XSS attacks. Input handling breaks down into three categories, validation (is an email an email?), sanitizing (take user data and rip out the bad stuff such as a script tag), and escaping (encoding potentially bad data in lieu of ripping it out). Create a CSP (content security policy) for your app. helmet was recommend to help with as much.

There was an Angular routing talk by John Niedzwiecki at AngularMix.

He recommends using CanActive with a role guard to safeguard if someone has permissions to visit a route. Also, I was surprised to learn that the lazy loading of an app may selectively not lazy load content that realistically the immediate user has no way of seeing because they are walled off from it by way of permissions restrictions and this all ties into the guards.

The code shown in the image is:

import { HomeComponent } from './home/home.component';
import { ResortDetailsComponent } from './resort-details/resort-details.component';
import { ResortResolverService } from './shared/resort-resolver.service';
import { RoleGuard } from './shared/role-guard.service';
import { SitemapComponent } from './sitemap/sitemap.component';
import { UserProfileComponent } from './user-profile/user-profile.component';
 
const routes: Routes = [
   { path '', redirectTo: 'home', pathMatch: 'full' },
   {
      path: 'admin',
      component: AdminComponent,
      canActivate: [RoleGuard],
      data: { roles: ['ADMIN', 'SUPER_ADMIN'] }
   },
   { path: 'error', component: ErrorComponent},
   { path: 'home', component: HomeComponent },
   {
      path: 'resort/:resortId/details',
      component: ResortDetailsComponent,
      canDeactivate: [ CanDeactivateGuard ],
      resolve : {
         resortName: ResortResolverService
      }
   },
   { path: 'sitemap', component: SitemapComponent },
   {

Saturday, October 28, 2017

I saw Justin James speak at the AngularMix on Sails.

Sails is a Node-server-flavored API framework build on top of Express which uses an ORM called Waterline to interface with Mongo whereas a more straightforward Express app might use Mongoose, an ODM or Object Document Mapper (think NoSQL) in lieu of an Object Relational Mapping, to crosstalk with Mongo.

I saw Vikram Subramanian speak on prerendering at the AngularMix conference.

Sometimes there will be the need for server-side rendering to make a fast initial paint of a web page snappy. Rob Wormald spoke to how this is really not in Angular's sweet spot in his talk. This sort of thing really breaks the SPA model. BrowserModule.withServerTransition is a way to attempt to get around the problem. The Domino server was mentioned in this talk. It provides a good enough DOM API to let you fake the DOM at the server to build up UI stuff there that you would then barf up to the front end.

RxJS Observables in Angular!

...was the name of a tech talk by Ward Bell (left) and Sander Elias (right) at the AngularMix convention. Observables are lazy and deferred by nature so if one isn't running you likely are not subscribing. One pain point that I've run into before was an inability to use Observables with a .NET Core endpoint which returned void for this very reason. I have hacked around the problem by returning a true value Boolean variable, but that is technically breaking with Roy Fielding's REST paradigm when hitting endpoints that use the PUT and DELETE verbs. (They should be fire and forget.) Is that the end of the world? No, but it did irritate me enough to ask Mr. Bell about it and he suggested that returning a 200 response with no packet as returning Ok(); is apt to do in a .NET Core controller action might be wise. You may have noticed that you are importing Observable from 'rxjs/Observable' but that you are not importing a specific type at all when importing 'rxjs/add/operator/catch' or 'rxjs/add/operator/map' so what are you really importing therein? In the second and third case you are monkey patching Observable to change up how it behaves and augment it with extra functionality. You may import 'rxjs' by itself and loop in way too much stuff, but this is not recommended as it will seriously affect your performance time. Cherry pick the operators you really need. The .debounce operator will create a delay of a third of second for new items coming in in an Observable stream and if you chase this downstream in a chain with .switchMap the switchMap will drop things in flight when hit so that there is only a mapping every third of a second reducing performance cost. Observables are always listening. This takes some getting used to and you may want observables to simply be less observant. Well, you may always just get a one-time-and-we're-done promise back from an observable by using .subscribe and, yes, if you do not then you are collecting something that is going to shepherded along until it is used with the async pipe to react to the latest data, probably inside of template markup. There is a way to do a .takeUntil which allows for listening up until a point. This could be the porridge that Goldilocks picks if you fear both a race condition and a performance issue, not too cold like .subscribe and not too hot like always listening. Here are some examples from the slides shown of the things I have just mentioned. First up is the cold porridge.

export class SimplefilmsComponent implements OnInit {
   films: Movie[];
   
   constructor(private filmsService: SimpleFilmsService) {}
   
   ngOnInit() {
      this.filmsService
         .getFilms()
         .subscribe(data => (this.films = data.results));
   }

 
 

Hot porridge:

export class SimplefilmsComponent implements OnInit {
   films$: Movie[];
   
   constructor(private filmsService: SimpleFilmsService3) {}
   
   ngOnInit() {
      this.refresh();
   }
   
   refresh() {
      this.errorMsg = '';
   
      this.films$ = this.filmsService.getFilms()
         .catch(err => {
            this.errorMsg = err.message;
            return [];
         });
   }

 
 

What is above might be interfaced with at a template like so:

<div *ngFor="let film of films$ | async">{{film.title}}</div>
<div *ngIf="errorMsg" class="error">{{errorMsg}}</div>

 
 

An example of using verbs:

@Injectable()
export class SimpleFilmsService2 {
   constructor(private http: HttpClient, private swUrlService:
         SwUrlService) {}
   
   getFilms() {
      return this.http.get<RootMovies> this.url
      
         .map(data => data.results)
         .catch(err => {
      
            console.error('GET failed', err);
      
            throw new Error('Sorry but can\'t get movies right now:
               please try again later');
      
         })
      }
   
   add(movie: Movie) {
      return this.http.post(this.url, movie);
   }
   
   get url() {
      return this.swUrlService.url;
   }
}

 
 

Fishing a URL line variable out of the URL line and using it to make a GET call:

ngOnInit(): void {
   console.log('MovieComponent initialized');
   
   this.currentMovie = this.route.paramMap
      .switchMap(params => {
         const id = +params.get('id');
         return this.filmService.getFilm(id)
            .do(movie => this.currentId = movie && movie.id);
      });
}

 
 

The debounce thing:

export class WikipediaComponent {
   
   constructor(private wikiService: WikipediaService) {}
   
   searchTerm = new FormControl();
   
   keyWords$ = this.searchTerm.valueChanges
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap(searchTerm => this.wikiService.load(searchTerm))
      .map(this.makeResultsPretty);

 
 

The .takeUntil thing:

export class TakeUntilComponent implements OnInit, OnDestroy {
   time: string;
   private onDestroy = new Subject<void>();
   
   constructor(private t: TimeService) {}
   
   ngOnInit() {
   
      this.t.time('TakeUntil')
         .takeUntil(this.onDestroy.asObservable())
         .subscribe
            time => (this.time = time),
            err => console.error(err),
            () => console.log 'TakeUntil completed')
         );
   }

 
 

Addendum 12/7/2018: The number in .debouceTime above is a number of milliseconds Again, this kinda behaves as capacitors paired with resistors might on a circuit board and things streaming in at an inconsistent rate are given a consistent rate via some buffering.

Friday, October 27, 2017

502. That’s an error.

I see this where my followers used to be on my blogger blog. There is an iFrame out to something that won't load. Come on Google, what gives?

Thursday, October 26, 2017

reflect-metadata shim is required when using class decorators

This error was calling out...

C:\Users\tom.jaeschke\Documents\whatever\client\node_
      modules\@angular\core\bundles\core.umd.js:384

 
 

...where it thought reflect-metadata as an object had a {} shape, in Googling against this problem. I found threads online that suggested that...

import 'zone.js';
import 'reflect-metadata';

 
 

...should go in the polyfills.ts file at the very top to beat this problem and that obviously reflect-metadata needs to be installed too. I put...

"reflect-metadata": "0.1.10",

 
 

...inside dependencies inside of package.json naturally. Also...

import './polyfills.browser.ts';

 
 

...in my main gateway-to-the-app main.ts file. And yet, on the other side of all this I still got the error. Alright well perhaps this setup which tries to run Jasmine is good for running unit tests but not tests against components. After all, how would it even know about main.ts to find the imports we add above? Today a coworker suggested using Karma instead as the test runner and we got as far as adding this to the package.json scripts:

"test": "karma start karma.conf.js",

 
 

These commands actually get the karma runner running:

install karma
install karma-requirejs
install requirejs
karma start karma.conf.js
karma run

 
 

Obviously, the installs only have to be run once. Part of the install sets up karma.conf.js which is full of configuration and you should doctor it up after the fact. The install process lets you prefly the configuration a bit. I still don't have things working. I am probably closer. More soon.

 
 

Addendum 10/27/2017: A better list of commands is:

npm install karma
npm install karma-requirejs
npm install requirejs
karma init
npm install jasmine-core
karma start karma.conf.js
karma run

Wednesday, October 25, 2017

ReferenceError: __extends is not defined

Per this, the fix for this error when attempting to run Jasmine/Karma tests in an Angular 4 app is to go into tsconfig.json and set...

"noEmitHelpers": true,

 
 

...to instead be:

"noEmitHelpers": false,

 
 

You will have to recompile JavaScript from TypeScript to get this to work as __extends will linger in your old generated JavaScript until you throw it away.

Use .remove in JavaScript to remove an item from a dropdown list at a particular position.

Do not try to do a .slice against the options array, instead something like this is more applicable, perhaps for removing that "PLEASE MAKE A SELECTION" default value after someone actually makes a selection:

if(this.foo.nativeElement.options[0].text == this.select){
   this.foo.nativeElement.remove(0);
}

Change around the color of copy at a dropdown list (at least in Google Chrome).

Just setting the color in CSS will make the copy one sees in the field itself beyond the dropdown list that appears when clicked before the control is ever clicked, the color specified, but unfortunately this will also color both the dropdown arrow (which implies "click me, I'll open a list") and also all of the list items. The solutions I have seen in Googling about an exception for the arrow all look a little painful. I think you have to swap out the arrow with your own .png or something. Anyway, you may set the color of the individual list items like so:

option.blackShow {
   color: #000000;
}
option.whiteHide {
   color: #FFFFFF;
}
.redUpFront {
   color: #FF0000;
}

 
 

The option tags get classes like so:

<div>Are you a boy or a girl?</div>
<select class="redUpFront" id="gender">
   <option value="" class="whiteHide" selected>pick...</option>
   <option value="M" class="blackShow">boy</option>
   <option value="F" class="blackShow">girl</option>
</select>

How may I tell if the computer in front of me running Windows 10 is 64-bit of 32-bit?

Right-click on the Windows icon button for opening the start menu and pick "System" to get a breakdown of specs for your PC.

When the TypeScript service won't recompile JavaScript in WebStorm...

...as described at the bottom of this, do note there is an icon/button for "Restart TypeScript Service" in the same spot that you may tap to refresh things.

Make a YouTube movie loop endlessly (easy version).

I don't know what I was thinking here, but in Google Chrome on a PC you may just right-click in a YouTube movie and pick "Loop" from the options that appear. When I pace in my apartment and daydream I like to play a music video off of YouTube repeatedly for background noise. I'll walk for fifty minutes to get some exercise without braving the cold.

Tuesday, October 24, 2017

Introduce Jasmine/Karma tests to an Angular 4 application which doesn't have tests.

I fought through this today. In attempting to run a TypeScript file with some tests in it with...

npm test

 
 

...I hit this error:

'Error: no test specified'

 
 

I got around that by putting the following the "scripts" section of package.json which breaks down along name, version, description, scripts, dependencies, napa, devDependencies, overrides, and engines properties:

"test": "jasmine",

 
 

Then, I hit this error:

'jasmine' is not recognized as an internal or external command

 
 

I added the following to the "dependencies" section of package.json:

  1. "jasmine": "2.8.0",
  2. "karma-cli": "1.0.1",
  3. "karma-jasmine-spec-runner-reporter": "0.1.5",

 
 

I ran...

npm install

 
 

...to loop in the three dependencies I just put in package.json. Then I hit this error:

No specs found

 
 

In the short term I changed...

"test": "jasmine",

 
 

...to first...

"test": "jasmine init",

 
 

...and then...

"test": "jasmine examples",

 
 

...before switching it back and after each change I ran...

npm test

 
 

...and that created a "spec" folder parallel to the "node_modules" folder which was also parallel to a "src" folder where the guts of the app were kept. Now when I ran tests it successfully ran some dummy tests which were put into that directory, the "spec" folder. Well, that is not where we want to run tests, is it? There is a jasmine.json file at spec\support\jasmine.json which had a line of notation like so in it:

"spec_dir": "spec",

 
 

I changed this to be:

"spec_dir": "src",

 
 

...and was soon back to:

No specs found

 
 

Back at spec\support\jasmine.json again, I addressed this by setting this line of configuration:

"**/*[sS]pec.js"

 
 

...to...

"**/*[sS]pec.ts"

 
 

.ts instead of .js, get it? Alright, I was now able to run the tests in the TypeScript file I had only to get this error:

SyntaxError: Unexpected token import

 
 

Alright, Jasmine cannot handle an import statement which is of ES6 so we are not going to be able to run tests against TypeScript tests directly. Instead the TypeScript tests need to compile to JavaScript tests and that means that the things they test need to be compiled to JavaScript too or else the dependencies will be jacked up. OK! I set the .ts back to .js, undoing the most recent change I give above, and then I set out to compile TypeScript. One may go to: View > Tool Windows > TypeScript YOURVERSIONHERE ...in WebStorm which will bring up a pane that has a "Compile All" icon/button to click on.

extend in Underscore.js

_.extend(yin, yang);

 
 

This is going to copy all of the properties from yang to yin which will get those properties in addtion to the ones it already had. It is basically like...

for (var property in yang) {
   yin[property] = yang[property];
}

Jasmine matchers for greater than and less than comparisons

Per this, they are:

  1. .toBeGreaterThan(13);
  2. .toBeLessThan(42);
  3. .not.toBeGreaterThan(69);
  4. .not.toBeLessThan(86);

 
 

Item three here is like less than or equal to and moreover item four above is like greater than or equal to. That is how you would hackily mimic that sort of functionality.

global install flag

This is the difference between...

npm install karma-cli

 
 

...and...

npm install -g karma-cli

 
 

...and, yes, g means "global" instead of local meaning that the thing you are installing should be available beyond the immediate project. I guess I would install anything installed globally locally too so that a folder is made in node_modules for the project. (I like to back node_modules up to source control personally.) I don't yet know where things get saved off to in the global way to go.

Monday, October 23, 2017

Wow! Everyone look at Kevin Hurwitz's LinkedIn!

Hilarious! Good luck with the new middle management role Kevin. That fits you perfectly! Ha ha ha ha!

TS2304:Cannot find name 'describe'.

Put this:

import {} from 'jasmine';

 
 

...at the top of the .ts TypeScript file where describe is red/mad to fix this error. I got this fix from here.

Sunday, October 22, 2017

Making a CMS is a difficult task for Angular as it requires server-side rendering.

This was a pain point brought up by Rob Wormald in a talk he gave at AngularMix. You may see the whole of his talk here. JSX syntax which is kinda like XML inside of JavaScript was mentioned in the talk as was vanilla-dom.

There was a talk by Alex Rickabaugh at AngularMix.

Angular microsyntax seems to be the formal name for the sugar syntax per this. This was one of the things mentioned in his talk which you may watch for yourself here.

In another AngularMix talk Igor Minar spoke.

See his comments here. They include: Yarn is deterministic. Deterministic is an adjective to describe how it locks down versions of dependencies. Travis CI and CircleCI are continuous integration tools. The Angular Testing Guide was mentioned. TTI or time-to-interactive is the amount of time it takes for an application to become responsive. BenchPress is a tool for measuring startup times.

 
 

Addendum 12/9/2018: A little bird tells me that Igor is basically responsible for the whole of version 1 of Angular, what is now known as AngularJS.

Nrwl!

Pronounced "narwall" and featuring a narwhale in its logo, Nrwl is a consultancy which helps others with Angular projects. At least two people work at this consultancy as Victor Savkin (left) and Jeff Cross (right) presented themselves and their company at the end of the Tuesday at the AngularMix conference. Their talk, which you may see here, was a refreshing break after a series of talks exclusively by Google's own employees and the first of only two talks that I saw at the conference which had two speakers. Savkin and Cross are themselves Google escapees and have built out a lot of Angular and AngularJS before spinning up a company of their in 2016. They have a product called Nx to address common problems such as race conditions. They decried a lack of standards in Angular apps and have a generator that calls ngRx calls in a predictable way. There is a generator that will try to migrate your existing AngularJS app to Angular. They are making a wrapper for fakeAsync in testing to make it easier to use. Annotations and decorations came up in this talk. This suggests that annotations are a language feature taking the shape of an array of metadata bolted onto an instance of class while decorators are functions developers might make themselves taking in instances of classes and passing them through while bolting metadata onto them.

Bazel was explained by Alex Eagle at AngularMix.

This holds a recording of the talk. Bazel itself is a build tool, good at understanding your packages and compiling. Hermetically, it is sealed airtight and you don't have to "clean" it between uses. You may build a build to chunks to be spread out amongst servers in a cloud.

The CDK was exhibited by Jeremy Elbourn at the AngularMix.

CDK stands for Component Dev Kit. You may read more about it here and Mr. Elbourn's talk, the best of the bunch from the AngularMix Tuesday, is given here. I don't believe this is quite out of development yet, but it is more or less stable and you may have at it as part of Angular Materials 2 here. Angular Materials are made up of CDK elements which are building blocks. Jeremy and his team tried to find functionality that came up as a need repeatedly and across commonly hand-rolled controls to make building blocks for such. The particular example that was on exposition in the talk was the challenge of a pane that appears popping out of another element upon interacting with the element. The list that appears when you click a dropdown would be an example. That is easy enough to make yourself, right? Well, in the CDK example that was shown there was emphasis on making the area that appears appear above the control if the control sits near the bottom of the browser so that one does not have to scroll down to see what appeared and below the control otherwise. What is more, if you move the scrollbar to move the downward sitting pane below the base of the browser it will auto-adjust to sit on top and when you scroll back up the thing on top will go below again, and so on. There is a lot more engineering to be done for this sort of puzzle than one might think of at an outside glance. I'm sure lots of devs have only realized hip deep into making their own controls what some of the challenges are. Other things mentioned included a11y which is an accessibility subpacket for screen readers, LTR/RTL reactionary capabilities (reading left-to-right versus right-to-left), and the utilization of SVG. The CDK is a set of engine parts to build up a rocket. Third parties rolling suites of controls themselves may utilize the CDK primitives. As you might imagine the CDK is going to have some dialogs, some list boxes, and yes, some tables in it. Tables seem to be the flagship of complexity and "doing too much" in any third party library such as DevExpress. Having bit into this challenge myself as suggested here I know that it isn't trivial to tackle this sort of thing. When I try to imagine myself writing something like the reactionary pop-out panes that either sit above or below a control I envision myself determining the height of the control and then figuring out how much screen real estate is left visible, etc. Hopefully the CDK will alleviate some of this heartache for a lot of people.

I saw Dan Wahlin speak on using Docker with Angular at the AngularMix.

This was one of those talks that had some going back in time nostalgia to it. Dan brought up WS_FTP in one of his slides and made me feel old. Apparently HotDog Professional was an old HTML editor. Macromedia HomeSite was also an older editor that was name dropped. MariaDB, in contrast, is a modern database platform. Anyways, not to get off topic... You may run an app in a Docker container and then move the container to any server. That was the thing to take away from this talk, the portability. Just prep your application to run in a container, not a server. That way the specific server may change. You may see/hear everything Mr. Wahlin said at this recording that was made. In terms of terms, think of an "image" as a blueprint like a class in C# and a "container" as an instance of the class. Docker Hub would be a good place to go to goof off with containers in getting started.

Saturday, October 21, 2017

A talk by Stephen Fluin at AngularMix was yet another talk I saw.

See the talk here.

Things said: ETag and Last-Modified are old school ways of caching. package-lock.json in an Angular app helps with locking down dependency versions and the use of Yarn for similar concerns was also encouraged. A polyfills.ts file in modern Angular CLI projects will govern what browsers you wish to support.

"Unit testing your Angular Applications" was a tech talk by Keith Stewart at ngHouston.

ngHouston is an Angular meetup group in Houston, Texas which met, the time I attended, at Improving's office. The talk I saw really was a good follow up to a full day workshop I attended ten days earlier at the AngularMix conference on October 9th which was spearheaded by Joe Eames. Keith Stewart works at CollabNet which owns Subversion and therein he is the lead UI developer for DevOps. A unit in a very basic form is one requirement or "the smallest thing you can get in an application" (Keith quote verbatim) and unit testing is distinct from both functional testing (unit tests in the browser) and also end-to-end testing which covers a large swath of functionality in browser-based tests. Protractor is for end-to-end testing though in the Protractor space the end-to-end tests, using the Selenium WebDriver, are confusingly referred to as functional tests in breaking with the definition that most expect. You go from the beginning to the end of a several step process in an end-to-end test. Karma and Protractor are made by the Angular team itself and Wallaby.js is a rival for Karma and Cypress.io a rival for Protractor. Wallaby is something you spin up to run in the background in an Electron shell all of the time you work and it meshes with your IDE (friendly with Visual Studio, Visual Studio Code, WebStorm, and Sublime Text) to put red, white, and green square dots by lines of code. White suggests code that is not covered by test, red a failing test, and green a passing test. Wallaby has metrics for test coverage. karma-coverage-istanbul-reporter was also recommended for test coverage. For all of the tools I have just mentioned, the talk basically focused on Karma/Jasmine tests. A good bit of this talk went over Jasmine matchers such as .toContain() to see if the copy inside of an HTML tag is what is expected in integration tests. .toEqual() and .toBe() are similar .toEqual() and .toBe() are similar with .toEqual() being akin to the == operator and .toBe() mimicking the === operator and matching with type as well as mere value too. .toMatch() is for regular expressions. .toHaveBeenCalled() and .toHaveBeenCalledWith() see if a function has been called and the later affirms certain arguments. In an example of both .toHaveBeenCalledWith() and a spy, Keith offered up this code:

gotoDetail(character: Character): void {
   const link = ['/detail', character.id];
   this.router.navigate(link);
}

 
 

Which was tested with spyon like so:

it('should navigate to the details page for the given character', () => {
   const spy spyOn(router, 'navigate');
   const character = new Character();
   character.id = 1;
   
   component.gotoDetail(character);
   expect(router.navigate).toHaveBeenCalledWith(['/detail', character.id]);
});

 
 

Keith had his own doctored-up version of the Tour of Heroes app around which he wrote some tests. Some code therein that was tested was:

getCharacters() {
   return this.http
      .get(this.charactersUrl)
      .toPromise()
      .then((response) => {
         return response.json().data as Character[];
      })
      .catch(this._handleError);
}

 
 

Alright, above we have an Observable that we just pop off to a promise (returning something once instead having ongoing listening) and then we cast off what we get back. The following test tests as much and it shows off .toEqual(), .toMatch(), and furthermore mocking.

it('should return characters', fakeAsync(() => {
   const character1 = new Character();
   const character2 = new Character();
   let result: Character[];
   
   service.getCharacters().then(characters => result = characters);
   lastConnection.mockRespond(new Response(new ResponseOptions({
      body: { data: [character1, character2] }
   })));
   tick();
   expect(lastConnection.request.url).toMatch(/app\/characters$/);
   expect(result.length).toEqual(2);
   expect(result[0]).toEqual(character1);
   expect(result[1]).toEqual(character2);
}));

 
 

Wow, what is lastConnection and how does it work its magic? Alright, here is all of the code upstream of the test above that is in the same file:

import { fakeAsync, inject, TestBed, tick } from '@angular/core/testing';
import {
   BaseRequestOptions,
   ConnectionBackend,
   Http,
   RequestMethod,
   RequestOptions,
   Response,
   ResponseOptions,
} from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
 
import { CharacterService } from './character.service';
import { Character } from './hero';
 
describe('CharacterService', () => {
   let service: CharacterService;
   let backend: MockBackend;
   let lastConnection: MockConnection;
   
   beforeEach(() => {
      TestBed.configureTestingModule({
         providers: [
            CharacterService,
            Http,
            { provide: ConnectionBackend, useClass: MockBackend },
            { provide: RequestOptions, useClass: BaseRequestOptions }
         ]
      });
   });
   
   beforeEach(() => {
      service = TestBed.get(CharacterService);
      backend = TestBed.get(ConnectionBackend);
      backend.connections.subscribe((connection: any) => lastConnection = connection);
   });
   
describe('#getCharacters', () => {
   it('should query the current service url', () => {
      service.getCharacters();
      expect(lastConnection).toBeDefined('no http service connection at all?');
      expect(lastConnection.request.url).toMatch(/app\/characters$/, 'url invalid');
   });

"Testing Angular Like a Boss!" was a daylong workshop by Joe Eames at AngularMix.

This was very insightful and a second tech talk on testing by a Keith Stewart at ngHouston back in Texas ten days later on October 19th really drove a lot of what I learned home and gave answers to questions I had. (I'll get to that too.) Joe went over the arrange, act, and assert approach to unit testing and put an emphasis on making tests DAMP (descriptive and meaningful phrases) instead of DRY (don't repeat yourself) in the name of making the tests readable (i.e. don't tuck too much logic up into a beforeEach). He encouraged using the Angular CLI, Karma, and Jasmine. By using the CLI (command line interface) I mean making a modern project friendly to both webpack and the Angular CLI. This would be the third version of an approach to an entry point and overarching wrapper of an application's architecture that has a consensus around it, the first being to use system.js, and the second being the use of webpack in a manual setup (you find a seed project online and you doctor it up) that jives poorly or not at all with the CLI. You should use the CLI from the beginning to prep your app including the webpack machinery. You may now do that with the CLI. That is new. ngdoc.io was suggested to be a good place to go for all sorts of documentation. Mr. Eames went over the concept of test doubles which he felt originally came from Kent Beck. He specified four varieties, those variations being mocks, spies, stubs, and dummies. Certainly I have used stubs and mocks in the C# space and have heard of spies therein too, but I found myself struggling to understand the strict definition of these concepts in the Jasmine/Karma testing paradigm, yet eventually it all made sense. The other tech talk I attended ten days later helped, and, again, I'll get to that. Spies take one of two shapes or, more likely, a hodgepodge of the two, either you are making a wrapper function around a function that acts as a passthrough taking in the same variables as the thing it wraps, handing those variables on, getting a response, and then handing the response back while also setting some state somewhere that may be tested for an affirmation that X happened, or you are stamping your own function over the top of a function that calls out to something complicated, perhaps an external dependency, in the name of making testing easier, appropriately isolated, and more predictable. Again, it is more likely a bit of both and I will have an example from the talk I saw ten days later to show off later. Stubs and mocks mirror their C# counterparts in that stubs are dummy objects full of convenience methods to use in lieu of what they might replace which might otherwise call out to external dependencies or do too much in some other way and mocks similarly provide convenience methods but not by the way of you merely hand-rolling an object to use in place of the object that would do something "bigger" in the proper workflows of the application. Just as mocking in C# brings in a bigger apparatus such as NSubstitute into play there too are similar scenarios in the Jasmine/Karma approach. I'll have an example when I give a blog posting on the Keith Stewart talk. The Joe Eames talk introduced dummies to me which are like empty stubs which only are used to fill in the requirement of an object that is demanded that yet doesn’t need to do anything. A nude JSON object that is made by opening curly braces and then immediately closing the curly braces is a good example of a dummy. Joe sees three kinds of tests, namely isolated tests, shallow integration tests, and deep integration tests. Isolated tests test merely a class and wall off other concerns with test doubles. Integration tests test components and their templates. The shallow variety tests just the immediate component and the deep variety lets tests reach into nested components within the component. Having said that, Joe does not encourage testing more than two levels deep. The convention I've seen before of putting a file holding a swath of tests immediately next to the thing that is being testing in the file tree of an application and moreover giving the file full of tests the same name as the file it tests save for the addition of adding "spec" just before ".ts" was maintained by Joe with a variant of also putting isolated, shallow, or deep into the name too. For example, he had a testing file in what I think was his variant of the Tour of Heroes app (a dummy app often used in tech talks as an example of a modern Angular application when showing off code) in some code he gave us which was named hero-detail.shallow.spec.ts and looked like so:

import { TestBed, fakeAsync, tick, async, ComponentFixture, inject } from
      '@angular/core/testing';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroService } from 'app/hero.service/hero.service';
import { ActivatedRoute } from '@angular/router';
import { FormsModule } from '@angular/forms';
 
describe('HeroDetailComponent (shallow)', () => {
   let fixture: ComponentFixture<HeroDetailComponent>;
   let component: HeroDetailComponent;
   let element;
   let heroes = [
      {id: 3, name: 'Magenta', strength: 4},
      {id: 4, name: 'Dyama', strength: 2}
   ];
   
   beforeEach(() => {
      const mockHeroService = {
         getHero: () => Promise.resolve(heroes[0]),
         update: () => Promise.resolve()
      };
   
      const mockActivatedRoute = {
         params: [{id: '3 '}]
      }
   
      TestBed.configureTestingModule({
         imports: [
            FormsModule
         ],
         declarations: [
            HeroDetailComponent
         ],
         providers: [
            {provide: HeroService, useValue: mockHeroService},
            {provide: ActivatedRoute, useValue: mockActivatedRoute}
         ]
      })
   
      fixture = TestBed.createComponent(HeroDetailComponent);
      component = fixture.componentInstance;
      element = fixture.nativeElement;
   });
   
   describe('ititial display', ()=> {
      it('should show the correct hero name & id', async(()=> {
         fixture.detectChanges();
         fixture.whenStable().then(() => {
            fixture.detectChanges();
            expect(element.querySelector('div').textContent).toContain('id: 3');
            expect(element.querySelector('div').textContent).toContain('Magenta');
         })
      }))
   })
   
   describe('ititial display fakeAsync', ()=> {
      it('should show the correct hero name & id', fakeAsync(()=> {
         fixture.detectChanges();
         tick();
         fixture.detectChanges();
         expect(component.hero).toBeDefined();
         expect(element.querySelector('div').textContent).toContain('id: 3');
         expect(element.querySelector('div').textContent).toContain('Magenta');
      }))
   })
})

 
 

The above shows off fakeAsync and tick which are vital concepts. The fakeAsync manages an asynchronous callout with test doubles (faking it) and then the line of code that has tick(); on it forces the pseudopromise to "come back" affecting state. There is also async instead of fakeAsync and flush instead of tick. async is another way to go about this with other syntax and is out of vogue compared to fakeAsync around which some embrace/consensus has developed. flush does what tick does but also carries back some reporting. You may want to create a directory of "matchers" which are helpers for things which come up over and over again in tests. Tour of Heros has a superhero feel to it and there is, in Joe's tests, a need to determine if an object is a hero and so a convenience matcher that checks to see if a JSON object holds three specific properties was written. Use the npm test command to run the tests at the command prompt. Mike Brocchi wrote the Angular CLI and Paul Irish refers to stamping a spy method overtop of a method in the very class you are testing as "duck punching" which Joe discouraged. If you have good separations of concerns and a distinction between components and services you shouldn't need to duck punch. An example for testing a service at a file dubbed hero.service.shallow.spec.ts was:

import { TestBed, inject, fakeAsync, tick } from '@angular/core/testing';
import { HeroService } from './hero.service';
import { Http, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
describe('HeroService', ()=> {
   let connection;
   
   beforeEach(() => {
      TestBed.configureTestingModule({
         providers: [
            HeroService,
            MockBackend,
            BaseRequestOptions,
            {
               provide: Http,
               useFactory: (backend, defaultOptions) => new Http(backend, defaultOptions),
               deps: [MockBackend, BaseRequestOptions]
            }
         ]
      })
   });
   
   describe('getHero', () => {
      it('should return the correct hero when called with a valid id',
      fakeAsync(inject([HeroService, MockBackend], (service: HeroService, backend:
            MockBackend) => {
         let matchingHero;
         const heroes = [
            {id:2, name: 'Rubberman'},
            {id:4, name: 'Dynama'}
         ];
         let mockResponse = new Response(new ResponseOptions({body: {data: heroes},
               status:200}))
         backend.connections.subscribe(conn => connection = conn);
         service.getHero(4).then(hero => matchingHero = hero);
         connection.mockRespond(mockResponse);
         tick();
         expect(matchingHero.id).toBe(4);
      })))
   })
})

Friday, October 20, 2017

AutoDetectChangesEnabled in Entity Framework

You may manually turn this off like so:

context.Configuration.AutoDetectChangesEnabled = false;

 
 

There is not really a good reason to do so. Maybe one use case might be in the name of performance in the short term when churning on something heavy, but in that case you will want to turn this stuff back on after the fact.

context.Configuration.AutoDetectChangesEnabled = true;

Swagger/Postman convenience magic

If you are hosting an API at https://www.example.com/ there is a way to utilize Swagger to give you a breakdown of all of the endpoints at https://www.example.com/swagger/ which are all testable right there at the long list of an HTML page that gets served via form controls. At my work, most of our endpoints will require a bearer token for permissions-sake. We have a setup in Postman to accommodate this. We past “bearer foo” to hand the bearer token into the Swagger interface with foo swapped out with something bigger.

Wednesday, October 18, 2017

font-weight: 800;

...is a good hack for when font-weight: bold; doesn't scream loud enough. 900 should be stronger yet! This has a cheat sheet.

Tuesday, October 17, 2017

When manually doctoring up an .edmx, you likely will also need to doctor up the generated classes.

Yesterday a coworker helped me with a surgery like this one. Specifically, I had made a tinyint column that mapped to a byte type at the C# classes and I needed to swap it out to an int/int shape instead. This meant altering the classes themselves too.

Monday, October 16, 2017

C# has Int16, Int32, and Int64 but no Int8.

Instead it has "sbyte" and a range that starts at zero instead of straddling zero without negative numbers from 0 to 255 is represented by the "byte" type. A tinyint type T-SQL column will be cast to a byte type getsetter at a C# class in Entity Framework's paradigm, not an int type getsetter.

Sunday, October 15, 2017

I saw an AngularMix talk on ngUpgrade.

It was put on by Miško Hevery. You may see it here. ngUpgrade is the way to get Angular 1 to play nicely with Angular 2 and up. Angular 2 code can get wrapped so that it may live in Angular 1 code and Angular 1 code may get wrapped so that it may live in Angular 2 code. There is a distinction between ngUpgrade Full and ngUpgrade Lite. In the full version the two versions really become one app together and in the lighter version there are basically two separate applications just touching each other when appropriate. One of the big distinctions is thus whether or not change detection cascades across everything or stays walled-off to one code base. There is also the concept of ngDowngrade for making the Angular 2 stuff downwards compatible.

The keynote at AngularMix was given by Brad Green of Google.

This talk (see it here) was varied and heavily plugged others who were to talk. There was some meat though. Templates are "statically analyzable" as anything in a template can be affected by a script. codelyzer is a linting tool. PLX 2.0 is a unified business intelligence platform from Google. Angular Labs as a concept will refer to things (the collection of things) which have been through the design process which are not yet fully baked. Angular Materials is a library of UI elements for Angular. Lightning components are Angular UI controls specific for use with Salesforce. shopstyle.com is an example of a progressive web app. There is a thing called Domino on the server side that makes server-side rendering not hurt and get back up to the frontend quickly. NativeScript lets you build native mobile apps with Angular and TypeScript/JavaScript.

I saw Daniel Rosenwasser speak at AngularMix!

scriptsharp and GWT were given as examples of trying to solve the problem TypeScript solves once upon the time. The former lets you write stuff in C# and then render out JavaScript with it and the latter is the same thing with the C# part just swapped out with Java and herein GWT is pronounced "gwit" and stands for Google Web Toolkit. It really wasn't until CoffeeScript came along that human beings had the Aha! moment of realizing that we could just make a new language that compiled to JavaScript in lieu of some terrible translator. Of course, everyone hates CoffeScript, so something new was needed. That brings us to Daniel Rosenwasser, the Microsoft Program Manager managing TypeScript who, yes, was the one giving this history lesson as history is written by the victors.

His talk, following that opening, was a smorgasbord of nuggets of information on TypeScript such as:

  • Contravariance exists! The image above shows off a change coming to TypeScript with regards to strictFunctionTypes. If Dog extends Animal, you may not (one day) hand in an array of Animal at a function signature that expects an array of Dog. However, this is a new restriction coming that does not immediately exist in TypeScript. An example of where contravariance is allowed materializes when a type defined as a union has an instance which gets eventually more strictly defined as one of the classes in the union. Daniel typed up an example of this which I didn't quite retain in my notes, but a good paraphrasing might be:
    class Cat{
       speak():void {
          alert("Meow");
       }
    }
    class Dog{
       speak():void {
          alert("Bark");
       }
    }
    type Animal = Cat | Dog;
    let contravariance = function (animal:Animal):void {
       let dog = (animal as Dog);
       dog.speak();
    }
    contravariance(new Dog());
  • The term "narrowing" came up in another, different example that had a union in it, and one I can recreate verbatim, which started out like so:
    function sendUpdates(emailAddr: string | string[]) {
    Somewhere in the function we have some branching logic around the possibilities of the union like this:
    if (Array.isArray(emailAddr)) {
    This sort of use of control flow analysis is given the moniker: narrowing
  • Somewheres between verbatim and paraphrasing I offer up this quote: "There are two types of programming languages, those that people badmouth and those that people don't use."
  • .dts files are a set of declarations for what exists at runtime. Under the hood, these tell TypeScript about what your JavaScript looks like at runtime making, I would suspect, some of the compiler safety and Intellisense around that feasible.
  • A ts-ignore suppression comment looks like so:
    let x: number;
    //@ts-ignore;
    x = "hello";

    ...and does what you think it does. The comment is decorating the line immediately below it and keeping the compiler from objecting.
  • The Elvis operator in TypeScript is akin to the safe navigation operator in C#. You may dot, dot, dot out to something confident in your ability to break Demeter's Law (and open Pandora's Box) provided that you lead the dots with question marks. You just end up with a null assignment should something break somewhere along the chain. Have fun troubleshooting that! (Only fools rush in.)

Saturday, October 14, 2017

At AngularMix I saw Erik Haddad speak on progressive web apps!

I first heard of progressive web apps at this talk out at Google's San Francisco facility, but I didn't really get the big picture until I saw this other talk by Erik and they look about as intimidating as Mr. Haddad does in this photo I snapped of him. There is a lot to learn about service workers that I know I will have to learn one day, but also not soon. PWA support is not going to work in all browsers as not all browsers accommodate service workers yet. Google Chrome has service workers, but not Internet Explorer, etc. and this lack of cross-browser compatibility means that niche things will use them in the short term, not me. One example is progressive web apps in the mobile space. Where as you might use Ionic or Ionic 2 to make a traditional hybrid application in HTML5 in lieu of building natively for both iPhone and Android which sucks, you could alternatively make a PWA which is, yes, technically also a hybrid app, but it is one that goes out of its way to behave like a native app. It will have a local cache managed by a service worker. The service worker will sync things back up to a database at a server somewhere when it can. It thus makes the online/offline thing painless and you may use the PWA disconnected just like a native app. The concept of three-way databinding thus exists in this space with the UI, the cache, and the remote data storage online, be it what it may, being the three actors. Push notifications are a part of PWAs too and this too leans on service workers. You will be able to specify serviceWorker: true somewhere in apps that are Angular 5 or better to empower ngsw for caching. (Again, think of the looming future not the immediacy.) To actually build out a PWA you might use AngularFire2 which is a hodgepodge of modern Angular and Firebase playing nicely together. You can pretty much just drop Firebase into place per Erik with just six lines of configuration and have a real time database, authentication, and storage. Lighthouse was mentioned in this talk too. It used to be a standalone Google Chrome extension but now its abilities are just rolled into the Google Chrome Developer Tools you see when you press F12. Erik said this thing was at an "Audit" option under "Performance" but in the version of Chrome I have on my laptop (61.0.3163.100) I just see an "Audits" header across the top where it says: Elements, Console, Sources, Network, Performance, Memory, Application, Security, Audits ...This tool rates your app on performance and gives you suggestions as to how to clean stuff up to be more compliant with good design in the serverless space. Cloud Functions for Firebase let you defer some heavy lifting to the cloud, when it is available, so that you may do some things there in the name of keeping your app's footprint small. The resizing of images was given as an example.

I saw John Papa speak at AngularMix.

You can see the talk for yourself here, so in many ways I don't need to offer a blog posting. The talk was on Angular CLI and builds. ng build as a command runs a development build, creating dist files in a dist folder, etc. Do not import all of RxJS at once. It is too heavy. Just import the operators you need. You want to keep the production build lean.

Updating the database in Entity Framework's code first paradigm is explained by Julie Lerman at AngularMix.

I have run into a pain point with Entity Framework's code first approach and, as of this week, have been delighted to learn that it is not a bad as I am making it out to be in my head. The fact that I've not yet worked professionally on a team that does the code first thing leaves me in the dark, but now there is a little more light thanks to a talk by Julie Lerman at the AngularMix conference. Alright, as I already knew, you have to have a migration script to update the database. I did not realize how easy it was however. This has some steps and per Julie's talk this would be a good command line command to make the first script:

  • dotnet ef migrations add init
     

It's gonna make some gunk inside of your Visual Studio solution (looks like C#) in one file that you may just run from there with this command line command:

  • dotnet ef datatable update
     

Build your solution afterwards like so:

  • dotnet build
     

I'm sure these commands vary a bit, and especially so when you update the initial script. The second of the links I provide here seems to have a bit different syntax than what Ms. Lerman showed off. Ms. Lerman has a bunch of Pluralsight content/trainings on Entity Framework too. I would imagine they get into this subject as well.

AngularMix

Alright, the AngularMix was this week. I was in Orlando, Florida for the first of what is hopefully an annually reoccurring conference on Angular 2 and up. The event was held at Universal Studios at the Loews Royal Pacific Resort. Richard Campbell and a partner of his were the keepers of the event, coordinating things.

I'm exhausted. I promise I will type up blog postings on each of the talks I saw, but it is going to take me some time as there was so very much to see and do. Thanks to Jeremy Elbourn, Ward Bell, and Thomas Burleson for letting me catch dinner with them Wednesday night. It was intriguing. I learned a lot about the now extinct giant birds of New Zealand. We seemed to reach a consensus that "Much Ado About Nothing" was one of the easier of Shakespeare's works to digest.

It wasn't Jeremy Elbourn, Ward Bell, or Thomas Burleson, but someone (I will not drop the name.) confessed that the decision to keep the name Angular in changing from Angular 1 to Angular 2 when there was such a giant leap for mankind was strictly a marketing strategy. Google had to find someone with enough Stack Overflow points to change the topics that were "Angular" to "AngularJS" to accommodate this.

I saw John Wang speak at ONETUG on IoT on Thursday night.

And, he would want you to know that just around the corner is Tampa Code Camp. I'm confident of this as he certainly kept chatting me up about it. IoT is of course the internet of things, but ONETUG is, perhaps less obviously, the Orlando .NET User Group. Orlando and Tampa are cities in, yes, the U.S. state of Florida. I drove in from Texas for something else and thought that I might as well hit the .NET User's group in Orlando, hosted at the public library on East Central Boulevard, while I was there. Smartdust is a buzz word. Raspbian is the default operating system for Raspberry Pi but you can also use Windows 10 now in later devices. Yawn! Who cares right? Well, I didn't really care when I started this talk but I was pretty intrigued as it went on. I really had no idea of the scope of what is possible. Tesla has its cars broadcasting their locations up to a bus (from omnibus, a system that transfers things from one locale to another more smartly than could be done in the absence of a system) and that is used to crowdsource the traffic amounts at maps! Each car has 4G (fourth-generation wireless, the latest stage in broadband mobile chitchat) ATT connection. I don't know what CLEAResult does in modern times but when I was on a consulting team there back in 2009 or 2010 or whenever they helped set timers for when the heating or air conditioning should kick on in a large facility like a school, ideally cooling the facility before the day really gets going and then letting the cool air sit during the day. If you were to make a pie chart of all of the electrical costs for a building and pieces of the pie were, I dunno, the lights and maybe things plugged into electrical outlets... Well, the biggest piece of the pie would be the heating, venting, and air condition system. The HVAC slice of the pie would be over half of the pie, so it is really a place to focus to bring down electrical costs. There is no longer a reason, as best as I can tell, to consult with CLEAResult for this though. You can just program a device in modern times that governs the timing. You can probably just Google for suggestions too for how to pick times. Why pay for consulting? The latest Apple Watch will warn you should your heart rate grow high. There is a crappy CCTV camera called Mirai that comes with a preset default username and password for an admin account and runs by default on a pre-slated port. These talk to the internet so that you may buy one at WalMart, set it up yourself, and then watch your camera online. Awesome! When you don't reset the default port and password, hackers can break in without much hacking. Not only is this bad in and of itself and really a reason to perhaps buy expensive stuff in lieu of cheap stuff (Mr. Wang's recommendation) but more interestingly yet one hacker took over enough of these over time to orchestrate a DDoS attack against Airbnb using all of the cameras as zombie computers. MXChip IoT DevKit was recommended as a good go-to to start playing with this stuff. It has microphone, headphone, sensors for humidity/temperature/pressure, accelerometer to measure how fast the device is going, gyroscope for gauging direction and "Am I upside down?" stuff, and a magnetometer (the compass) too. Beyond using HTTP for messaging you may also use other protocols such as Advanced Message Queuing Protocol or AMQP. The default/standard is MQTT or Message Queue Telemetry Transport and it just messages bits in really light messages, has pub/sub, and goes back to the 1980s. This talk also went into how to architect Azure to approach this space and its challenges. Remote monitoring and predictive maintenance each have a solidified model in Azure architecture.

Friday, October 13, 2017

DirecTV

Alright, I have returned to Deer Park, Texas from Orlando, Florida. I promise I will write up blog postings on everything I saw there. I made a car trip of this adventure and both coming and going stayed a night in Tallahassee, Florida. On the stay there going in I had DirecTV, a service that streams in from a satellite, in the hotel room and it screwed up like so when disrupted by Hurricane Nate:

I was trying to watch "Mike and Dave Need Wedding Dates" on HBO and I kinda lost some stuff around the seam between the second and the third acts. Lame! I had never played with DirecTV before. This movie is hardly "Citizen Kane" in quality but I still wanted to see it.

Sunday, October 8, 2017

Orlando!

Fun fact: Orlando, Florida, USA is the city on Earth that gets the most tourists in a given day. The last time I checked it got roughly twice the visitors on an average day than Mecca, Saudi Arabia. Epicurean excess trumps religion! Anyways, I am there now. I am at Universal Studios for the AngularMix conference. I am originally from Florida so I drank my fill of Disney World once upon a time and haven't been in this city since I was fifteen as... who cares? But anyways, I am here now and I'm sure I'll be having plenty of fake plastic fun.

This is what I am doing for a conference this year. All of the conference stuff has dried up in Austin and I have moved out of the city to Deer Park, Texas anyways. Code Camp is long gone. There was that MeasureUP thing that Clear Measure put on that was like a watered-down Code Camp for two years too, but it too seems to be discontinued. Whatever happened to the video recordings from the 2016 MeasureUP? Whatever. Don't bank on the Austin community anymore. It has changed.

 
 

Addendum 10/14/2017: Alright, here are the videos after all! Thanks to Colin Pear and Rayne Fulton for helping with this.

future thoughts

I've had a few conversations about the dynamic forms in Angular 4 with coworkers and whether or not they are a good thing or a bad thing. I don't yet have enough experience to have a strong opinion. I can see how they might speed some things up with easy-to-slap-on validations and how once a dirty flag is true at a control and it thus makes the dirty flag true for the whole of the form you could disable a submit button based upon that with ease. However, should validations just come from the model and be tied to the model? If I have two different forms for the same model am I breaking the DRY principal by writing validations twice? A coworker feels that the validation rulesets should be tied to the models all the way down at the C# level, be serializable and thus handable over the wire to the TypeScript side, be run at the TypeScript side, and then, upon a form submit, be rerunnable at the C# side because you should not trust client-side validations. He apparently has a self-rolled pattern for this and is vocal about how Aurelia solves the problem better. Me? I am still developing an opinion.

Friday, October 6, 2017

modularity in TypeScript

As a concept this is the whole art of decorating classes with the export keyword and then looping those classes in as imports in another file.

SQL Value Functions

substring and convert are examples of these. These are built in transforming machines. This has a little list.

Thursday, October 5, 2017

In the table-cell approach in CSS the padding comes out of the width in lieu of adding to it.

How wide will this be? 135 pixels? Wrong! It will be 130 pixels wide.

.floatLeft {
   float:left;
   width: 130px;
   height: 25px;
   background-color:blue;
   display: table-cell;
   text-align: right;
   padding-right: 5px;
}

 
 

This is at least true (the reality) in Google Chrome.

Wednesday, October 4, 2017

Assignments which accidentally use a double equals operator will not make the compiler squawk in TypeScript.

Consider this C#:

int a = 13;
int b = 42;
a = b;

 
 

And then consider introducing this typo:

int a = 13;
int b = 42;
a == b;

 
 

Alright, the compiler is going to throw a temper tantrum at that, huh? Well what if we took this TypeScript...

let a = 13;
let b = 42;
a = b;

 
 

...and screwed it up like this:

let a = 13;
let b = 42;
a == b;

 
 

Well, this may come as an unpleasant surprise (it sure did for me) but the compiler will not get cranky about this. I guess you are just dumping a comparison on a line by itself and the comparison, be it true or be it false, will just silently do nothing without any other code about it. In other words, your assignment silently fails. I guess this is legitimate JavaScript and therefore legitimate TypeScript. Fun!

What is the difference between const and let in TypeScript?

const is just like let except that you cannot reassign const variables.

Tuesday, October 3, 2017

Mandalay Bay

The only time I have been to Las Vegas, Nevada it was in 2015 for Black Hat which was at the Mandalay Bay casino. In deciding where to stay it was easy to conclude that I should stay at Mandalay Bay too and so I did. I was there for a few nights.

As of this week Mandalay Bay's name will be tied to one thing in history, the deadliest rampage killer rampage in American history. A gunman (Stephen Paddock) fired from one of the hotel rooms on the thirty-second floor outward into a Jason Aldean country music concert and then formulaically killed himself when cornered by law enforcement enforcers. Is anyone going to want to vacation here again? Are they going to have to tear down the casino and put something else in its place?

This casino is the Southernmost of all the casinos on the Vegas strip. The "Bay" part comes from a very impressive swimming pool that is there that fakes waves and what not. I have photos of it, but they really are not that good as far as photos go. I also have a not so great photo of the view out my hotel window overlooking the then empty spot which housed the concert event and it's not that hard to imagine the shooter's perspective, but that photo too is not really a good photo. "Mandalay" is a Myanmar/Burma city and I can't make sense of that part of the name like I can the "Bay" bit.

a reflection-based solution for drinking up records with LinqToExcel when there are not explicit column names

I'm going to have a "NoteAttribute" attribute as described here only AttributeTargets.Method will be replaced with AttributeTargets.Property as we will be dealing with the pseudogetsetters that are auto-properties in lieu of methods. I'm basically tackling this problem and keeping the logs variable as descibed only it will be a List<RowNoHeader> instead of an IQueryable<RowNoHeader> but this change like the other change is really a pretty small thing. The important thing to know is that the records we drink off of a LinqToExcel scrapping end up in the variable called logs. We use it like so:

int pseudoHeaderPosition = 8;
List<WeldLog> weldLogs = new List<WeldLog>() {};
int outerCounter = 0;
Dictionary<int, int> dictionary = new Dictionary<int, int>();
Type type = typeof(WeldLog);
PropertyInfo[] propertyInfos = type.GetProperties();
while (outerCounter < propertyInfos.Length)
{
   var metadata = propertyInfos[outerCounter].CustomAttributes.ElementAt(0)
         .ConstructorArguments[0].Value.ToString().Trim();
   int innerCounter = 0;
   while (innerCounter < logs[pseudoHeaderPosition].Count)
   {
      var pseudoHeader =
            logs[pseudoHeaderPosition][innerCounter].Value.ToString().Trim();
      if (metadata == pseudoHeader)
      {
         dictionary.Add(innerCounter,outerCounter);
      }
      innerCounter++;
   }
   outerCounter++;
}
outerCounter = pseudoHeaderPosition + 1;
while (outerCounter < logs.Count)
{
   WeldLog weldLog = new WeldLog();
   foreach (KeyValuePair<int, int> keyValuePair in dictionary)
   {
      var setting = logs[outerCounter][keyValuePair.Key].Value;
      SetIt(weldLog, propertyInfos[keyValuePair.Value], (dynamic)setting);
   }
   weldLogs.Add(weldLog);
   outerCounter++;
}

 
 

Alright, clearly (well, maybe it's not so clear) we will end up with the weldLogs variable hydrated with WeldLog records on the other side of this procedural blob and clearly WeldLog has a bunch of auto-properties on it and those auto-properties have at least one attribute each that is getting found as the first attribute for every auto-property. As you might surmise, the attribute is the NoteAttribute. The code above assumes that the 9th row of the Excel sheet contains pseudoheaders for columns (while the first 8 rows contain a fat header with various notes) and the rows after have the actual data. The WeldLog POCO looks like so:

namespace WelderConsoleApp.Logic
{
   public class WeldLog
   {
      [Note("Area")]
      public string Area { get; set; }
      
      [Note("Drawing #")]
      public string DrawingNumber { get; set; }
      
      [Note("Item #")]
      public string ItemNumber { get; set; }
      
      [Note("Weld #")]
      public string WeldNumber { get; set; }
      
      [Note("Unit")]
      public string Unit { get; set; }
   }
}

 
 

What about the SetIt method which clearly uses some dynamic magic? It looks like so:

private void SetIt(WeldLog weldLog, PropertyInfo propertyInfo, object setting)
{
   
//do nothing
}
 
private void SetIt(WeldLog weldLog, PropertyInfo propertyInfo, string setting)
{
   propertyInfo.SetValue(weldLog, setting);
}
 
private void SetIt(WeldLog weldLog, PropertyInfo propertyInfo, System.DBNull setting)
{
   
//do nothing
}