Thursday, August 29, 2019

Get the date when a file was last modified in C#!

using System;
using System.Collections.Generic;
using System.IO;
namespace FileCrawling
{
   class Program
   {
      static void Main(string[] args)
      {
         Dictionary<string, DateTime> dictionary = new Dictionary<string, DateTime>();
         string whereAmI = @"C:\\DummyDirectory\";
         foreach (string filePath in Directory.GetFiles(whereAmI))
         {
            string fileName = filePath.Replace(whereAmI, "");
            DateTime modifiedDate = File.GetLastWriteTime(filePath);
            dictionary.Add(fileName,modifiedDate);
         }
         Console.Write("Files:\r\n");
         foreach (KeyValuePair<string, DateTime> keyValuePair in dictionary)
         {
            Console.Write(keyValuePair.Key + " unalt since " + keyValuePair.Value + "\r\n");
         }
         Console.WriteLine("\r\nPress any key to end.");
         Console.ReadKey(true);
      }
   }
}

 
 

Note that this will not crawl subfolders for files. Use Directory.GetDirectories for that per: this

Automatically close the console when debugging stops

Check the checkbox for "Automatically close the console when debugging stops" under Debugging under Options under Tools in Visual Studio 2019 to Automatically close the console when debugging stops. As of Visual Studio 2019 the console app will kind of sit open after you stop debugging and wait for you to press the return key.

Icons in Angular Material

See: this. And use this stuff like so:

<mat-icon>lock</mat-icon>

 
 

The key you fish out from the link I provide goes inside of the tag, get it? In this case I want to show the icon of a padlock so the word "lock" goes side of the mat-icon tag. You have to have Angular Materials installed within your Angular application to get this stuff afloat.

The 1903 update for Windows 10 would include kaomoji which is some further type of emoji support.

There are all sorts of bugs and errors in this thing. It is fat. The windows update from yesterday supposedly closed a lot of security holes.

Wednesday, August 28, 2019

Type "Firewall" at the start menu in Windows 10...

...to find "Firewall & network protection" which you should click on to open up "Windows Security" and hopefully therein see "Domain network (active)" and "Firewall is off." which means you are not blocking yourself.

Explore FileTable Directory

This option in the "Object Explorer" in SSMS under FileTables under Tables under a particular database should let you browse a pseudofileshare where you may tuck away files to.

Tuesday, August 27, 2019

How do I unit test router.navigate(['/elsewhere']); in an Angular app?

You use the RouterTestingModule trick like so:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RealComponent } from './real.component';
import { RouterTestingModule } from '@angular/router/testing';
import { StubComponent } from './stub.component';
describe('RealComponent', () => {
   let component: RealComponent;

   let fixture: ComponentFixture<RealComponent>;
   beforeEach(async(() => {
      TestBed.configureTestingModule({
         imports: [
            RouterTestingModule.withRoutes([
               {
                  path: 'elsewhere',
               component: StubComponent
               }
            ])
         ],
         declarations: [ RealComponent, StubComponent ]
      })
      .compileComponents();
   }));
   
   beforeEach(() => {
      fixture = TestBed.createComponent(RealComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
   });
   
   it('should create', () => {
      expect(component).toBeTruthy();
   });
});

 
 

StubComponent better be damn simple:

import { Component } from '@angular/core';
@Component({
   selector: 'stub',
   template: 'n/a'
})
export class StubComponent {
   constructor() {
   
   }
}

 
 

StubComponet likely needs to be ceremonially called out in one of your real modules too and not just the pseudo, on-the-fly "module" inside the test as if it is not mentioned somewhere as a reference it may break your production build.

How do I unit test an Angular component that has Angular Materials in it.

In the imports in the test use ReactiveFormsModule (and maybe BrowserAnimationsModule too).

 
 

Addendum 9/7/2019: I think it might be MaterialModule that you have to loop in.

 
 

Addendum 9/10/2019: MaterialModule herein, which I saw in a friend's application, is likely something that only exists in her application. That module probably imports a great deal of things from '@angular/material' such as: MatInputModule, MatGridListModule, MatTooltipModule, MatBadgeModule, MatButtonModule, MatDialogModule, MatToolbarModule, MatSidenavModule, MatIconModule, MatListModule, MatCardModule, MatProgressBarModule, MatPaginatorModule, MatSortModule, MAT_DIALOG_DEFAULT_OPTIONS, MatProgressSpinnerModule, MatSelectModule, MatDatepickerModule, MatNativeDateModule, MatCheckboxModule, MatRadioModule, MatExpansionModule, MatAutocompleteModule, MatSnackBarModule, MatTableModule, and MatStepperModule. In other words, you need to import that thing from '@angular/material' that your particular module really needs to not break. Everything but MAT_DIALOG_DEFAULT_OPTIONS fills the list of imports and exports at MaterialModule. This has some notes on MAT_DIALOG_DEFAULT_OPTIONS and the hasBackdrop option for example sets or prevents a transparent background behind a modal. MAT_DIALOG_DEFAULT_OPTIONS goes in the providers like so:

{ provide: MAT_DIALOG_DEFAULT_OPTIONS, useValue: { hasBackdrop: true } }

Build expired

This is some sick error that will occur in Azure DevOps and keep your pull request from being committed. It is due to you trying to roll the build number backwards because you manually incremented it, yes, but others have gotten code into the build while you were working. I guess every time I am about to commit I need to commit, switch back to master, pull, get the master's build number, switch back to my branch, increment the build number with regards to what the master's build number was a second ago, recommit, switch back to master, and then merge in and finally do the pull request. Merging will forever be my Achilles' heel, the thing I am the worst at as a developer, the thing I don't want to think about.

Blizzard Entertainment

They give us WoW.

Kronos Incorporated

These guys make timetracking software and that ilk of things.

Monday, August 26, 2019

Can't bind to 'formGroup' since it isn't a known property of 'form'.

When you get this error in a test add CommonModule, ReactiveFormsModule, and FormsModule into the imports.

How do I run Windows Explorer as Administrator?

Run the command prompt from C:\Windows\System32\cmd.exe as Administrator and then run the command:

explorer.exe

It looks like you may implicitly upcast scalar types in C# to their nullable counterparts.

You may hand a DateTime into a method signature wherein a DateTime? is expected, etc. By the way the difference between a scalar and a primitive is that primitives are just reference types.

LANtastic

You ran a LAN with it and it was fantastic! You did the peer-to-peer (P2P) thing to share files (there was no hub, the computers were equals) and it was DOS-based.

Sunday, August 25, 2019

Do a .get off of a FormGroup to fish out a FormControl in an Angular application.

Assuming...

const form = new FormGroup({
   foo: new FormControl('bar'),
   baz: new FormControl('qux')
});

 
 

...you could do something like so:

console.log(this.form.get('foo'));

 
 

"ASP.NET Core 2 and Angular 5" by Valerio De Sanctis points at this trick on page 338 and this has some more about it.

Saturday, August 24, 2019

In an Angular application a FormControl has errors hanging off of it as a property.

"ASP.NET Core 2 and Angular 5" by Valerio De Sanctis mentions this on page 336. It suggests that required hanging off of errors as in errors.required will be true if there is an error of that specific shape with the FormControl. This suggests errors is of a type called ValidationErrors (or just null) and this further suggests other Boolean properties off of errors like errors.email and errors.minlength too. Both of the links I give here are going to be for versions of Angular beyond Angular 5 however.

I saw Rick Bielawski speak on PowerShell at PASSMN on Tuesday night.

There is no multithreading in PowerShell. The PowerShell ISE (Integrated Scripting Environment) is kinda like an IDE (Integrated Development Environment) for PowerShell. There is a pane at the right that has tabs to various .ps1 files. You may run the whole of a file with F5 or you may highlight just a piece of the file, perhaps a line, and then click F8 to run just that bit of the file. Chasing a variable containing tabular data with Out-GridView will barf up a separate window with a tabular recordset format that is easily portable to Excel and column-filterable by way of some dropdowns. There is no command called help so help sql will just find all of the "everything" that has sql in it. Get-Help Get-Verb –ShowWindow will open a little help file on Get-Verb which gives you a list of approved verbs in PowerShell and obviously you may swap out Get-Verb with something else. Per Rick the thing that gives PowerShell all of its power is that everything is an object and you may dot off the object in the right pane of PowerShell ISE (heard a coworker pronounce it: "PowerShell Ice") and get IntelliSense as to what "hangs off" the object. ([string]1).GetType() is an example of casting to a string (use int for integers) and "string"|gm is an example of handing a string with "string" inside of it to the Get-Member cmdlet which reveals the properties and methods of an object. "simple".Length gives us 6 because that is how long "simple" is. dir *.ps1 lists all of the files that end in .ps1 while dir *.ps1|gm gives their details in tabular format and dir *.ps1|gm|fl in a sequential list dump wherein each list item had a lot of details. The cmdlet on the end here is Format-List in its shorthand form. dir variable:\ gives you all variables in scope. cd SQLSERVER:\SQL\WN-MNA1HXA1C585\ an example of "changing directories" into SQL Server and following that up with dir DEFAULT\DATABASES\Rick\tables navigates into the tables for a particular database wherein dir will just give a list of tables. To hand something in on the right side of the gm instead of using the pipe symbol you have to do something like gm -InputObject $env:Path.Split(';') or gm -i $env:Path.Split(';') more tersely. $env:Path.Split(';').count will give you the number of line items returned by the previous two commands. function t{} followed by t gives nothing and function t{$x = $env:COMPUTERNAME} followed by t and then by $x also does nothing because of the scoping of $x but function t{$env:COMPUTERNAME} followed by t will tell you the name of your computer. 1,2,3|ForEach-Object {t $_} hands in each of the leading numbers to t. A shortcut for ForEach-Object looks like so:
1,2,3|%{
   t $_
   'hi'
}

This is equivalent to 1,2,3|%{ t $_ ; 'hi' } as if you don't want to use a line break you may use a semicolon. In Install-Module SqlServer –AllowClobber the –AllowClobber overpowers a conflict. The event was once again held at Microsoft's offices in Edina and I took this second picture of Rick Bielawski as we were waiting to leave on the elevator out together. The first picture I took of him actually presenting is kind of weak as it is backlit by too much sun coming in a window. Other things mentioned at this event included the new version 2 of Microsoft HoloLens and Hyperion which is a company that Oracle bought which offers products/software in the BI (business intelligence) sphere of things. Joshuha Owen gave a lighting talk on a PowerApp he made with PowerApps at the very end of the evening. His creation used Flow (which allows one service to talk to another service and which is very drag-and-drop and trigger-driven like PowerApps) to talk to Custom Vision (from PowerApps), a ReST API for AI (artificial intelligence) for image recognition. AI Builder in the PowerApps space itself is an alternative to Custom Vision. Logic Apps is an alternative to Flow but it is more geared to the enterprise level of things. You have to feed Custom Vision at least twenty five images to get it to start recognizing a pattern, but the more you feed it the better.

Friday, August 23, 2019

UUNET

It was an ISP. It was bought by Verizon at some point. The name comes from UUCP which is Unix-to-Unix Copy, a protocol for sending commands/data/files from one computer to another (wherein those computers are of Unix I'd imagine). I recall the name UUNET being dropped in a TV commerical that had Michael Jordon in it. I thought of it today.

the Scrum abstraction is most applicable in the consultancy/client relationship

Estimates are always wrong, so why do estimates at all? Why not just do Lean instead of Scrum? If you are product company building a product with in-house developers who are direct employees, yes, this is the way to go. You just work on what you have to work on anyways. Don't worry too, too much about how long it takes. It has to get done regardless. The reason to do Scrum is to have a burndown chart. The reason to have a burndown chart is for a consultancy to set expectation with its client that things will go off the rails a little bit and that sacrifices will need to be made. This insulates the consultancy from signoff on a waterfall project that balloons out of control because the upfront estimate of scope was wrong because estimates are always wrong. Scrum solves the "estimates are always wrong" problem by making bad estimates in a different way!

Make a radio button list from an array in Angular 7.

In the template for a component I have:

<table>
   <tr>
      <ng-container *ngFor="let fileFormat of fileFormats; let i=index;">
         <td>
            <input type="radio" name="format" [value]="fileFormat.Extension"
                  [checked]="i==0">
         </td>
         <td>
            {{fileFormat.PublicFacingName}}
         </td>
      </ng-container>
   </tr>
</table>

 
 

In the TypeScript for the component itself the fileFormats variable is an Array<FileFormat> which is hardcoded in the constructor like so:

this.fileFormats = [
   new FileFormat(".pdf", "PDF"),
   new FileFormat(".csv", "CSV"),
   new FileFormat(".docx", "Word"),
   new FileFormat(".xlsx", "Excel")
];

 
 

FileFormat looks like this:

export class FileFormat {
   Extension: string;
   PublicFacingName: string;
   public constructor(extension:string, publicFacingName: string) {
      this.Extension = extension;
      this.PublicFacingName = publicFacingName;
   }
}

 
 

My CSS:

table {
   margin: 5px 0;
   padding: 0;
   border-spacing: 0;
   border-bottom: 1px solid #000000;
}
td {
   margin: 0;
   padding: 0;
}
td:nth-child(2n+0) {
   padding: 1px 10px 0 0;
}
tr {
   margin: 0;
   padding: 0;
}

 
 

We end up with something like so bro:

Business Email Compromise scams or BEC scams

The attacker pretends to be a corporate executive over email and writes someone in finance who might legitimately funnel funds to them if they were who they pretended to be.

Thursday, August 22, 2019

notes from a training at work on machine learning today

"A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P, if its performance at tasks T, as measured by P, improves with experience E." is a 1997 definition of machine learning by Tom M. Mitchell. In the classic example of an email spam filter being wary of emails that say "I am a prince of Nigeria." the T is classifying emails as spam or not, the P is the fraction of emails labeled correctly, and the E is watching you label emails as spam or not. Machine learning has existed for forty years in the shape of the random forest model. The linear regression of deep learning and tools like TensorFlow is a modern marvel.

Numerous variables demand a solution beyond appsettings.json methinks.

Instead in a .NET Core application in the assets folder you could have .json variables for various environments and just have that environment swappable by an Octopus Deploy variable. This may be needed for Power BI reports wherein all reports across dev, test, and prod have the same base URL and just vary in URL route by way of the gobbledygook of GUIDs in the route. This is not my idea. It comes from a coworker.

 
 

Addendum 8/27/2019: The assets folder is in the Angular frontend not the .NET Core app. Duh! Use a trick like this like so... At the top of the file by the imports:

declare var require: any;
const { excelUpload } = require('../../assets/access.json');

 
 

Farther downstream in code in a method have:

let powerBIpath: string = ` eq '${fileUpload.FilePath}'`;
if (document.URL.toLowerCase().indexOf("localhost") >= 0){
   powerBIpath = <string>excelUpload.dev + powerBIpath;
} else {
   if (document.URL.toLowerCase().indexOf("dev") >= 0){
      powerBIpath = <string>excelUpload.dev + powerBIpath;
   } else {
      if (document.URL.toLowerCase().indexOf("test") >= 0){
         powerBIpath = <string>excelUpload.test + powerBIpath;
      } else {
         powerBIpath = <string>excelUpload.prod + powerBIpath;
      }
   }
}

 
 

The guts of access.json are:

{
   "excelUpload": {
      "dev": "https://app.powerbi.com/reportEmbed?reportId=c9a234a8
...",
      "test": "https://app.powerbi.com/reportEmbed?reportId=6625dde8
...",
      "prod": "https://app.powerbi.com/reportEmbed?reportId=c5dcff33
..."
   }
}

 
 

You have to enclose the property names in quotes too or the crawling breaks.

Windows-K

...seems to be the hotkey to share your screen on one of the TVs at our work during a scheduled meeting.

Wednesday, August 21, 2019

How do I hand an IFormFile from the UI to infrastructure in onion architecture?

Open the .csproj file for your UI in Notepad. The TargetFramework XML tag (inside the PropertyGroup XML tag inside the Project XML tag wrapping everything) will denote which version of .NET Core you are using and you will want to mimic this version when installing .NET to another project in your solution in lieu of just grabbing the latest. Install .NET Core with this NuGet command:

install-package Microsoft.AspNetCore MyApp.Infrastructure -Version 2.1

 
 

The big problem with this is that in your core project you will also have to have an interface that understands IFormFile however, so maybe we don't want to go there after all. Let's undo:

uninstall-package Microsoft.AspNetCore MyApp.Infrastructure -Version 2.1

 
 

The better thing to do is probably to do just enough work in the UI to turn the IFormFile into a byte[] type bytes array to mimic what is here just enough to get the fileContent variable but not enough to actually write records with it. Defer the writing of a file to the infrastructure. Hand in the bytes array to the infrastructure.

dark mode

This is a setting for various apps wherein you may see white text on a black background in lieu of the black on white look of Notepad. When I say white on black I kind of mean light on black. It is a Lite-Brite effect.

an upward pointing equilateral triangle in whiteboarding

It means: a change/delta

calls to https://wabi-us-north-central-redirect.analysis.windows.net/powerbi/refresh/subscribe over and over!

When a PowerBI report is moved from imported data to "direct query" data in the on prem solution, the report will need to ping out whenever it refreshes data and this will be reflected in these calls. Basically this is akin to an observable. The calls should not be running in an endless loop. (If that happens, maybe you need to tweak settings. Maybe a particular report runs cyclically.) You should not be constantly refreshing. The ping out to the URL should happen as the user changes tabs at a report or changes something else. Also, there could be a series of calls upfront in upfront loading.

Tuesday, August 20, 2019

subscription spool

Here is a pattern which has emerged in the Angular 7 application I am working on. At a component we have a component-wide variable for holding all of the subscriptions to Observables that we will mess with on the TypeScript side like so:

public subscriptions = [];

 
 

We put stuff in like so:

ngOnInit() {
   this.subscriptions.push(
      this.store.select(getUserInfo).subscribe(user => {
         this.user = user;
         getNextSubscription(user);
      })
   );
}

 
 

We throw away everything like so:

ngOnDestroy() {
   this.subscriptions.forEach(item => {
      item.unsubscribe();
   });
}

 
 

The point of this is a management trick for managing more than one subscription. We just see one above, but there could be more, no?

when to for concurrency concerns

If I write some record locking workflow will I goldplate my app? Should I not just wait until the users complain of concurrency collisions as they probably will not? In my experience the times when you need to proactively think about concurrency have to do with scenarios in which a lot of people are dog-piling into the app during a tight window just in advance of a deadline.

Elara

It has to do with the touchpad on a Dell laptop. You may see this app as the last thing running when you go to shut down.

// tslint:disable-next-line: max-line-length

Alright this comment in TypeScript is supposed to allow you to not lint the following line of code. I am seeing some things online that suggest that the effect will in fact affect the next two lines and that as much is a known bug.

Pega CSSA

CSSA stands for certified senior system architect and it is a cert for the Pega stuff.

Monday, August 19, 2019

a coworker's trigger to prevent manual database changes

We only want database changes to occur via continuous integration and Octopus rolling out from Visual Studio 2017 database projects so a coworker put this together:

USE [EnterpriseConsumption]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [block_changes]
   ON DATABASE
   FOR CREATE_PROCEDURE
   , ALTER_PROCEDURE
   , DROP_PROCEDURE
   , CREATE_TABLE
   , ALTER_TABLE
   , DROP_TABLE
   , CREATE_FUNCTION
   , ALTER_FUNCTION
   , DROP_FUNCTION
   , CREATE_INDEX
   , ALTER_INDEX
   , DROP_INDEX
   , CREATE_VIEW
   , ALTER_VIEW
   , DROP_VIEW
   , CREATE_TRIGGER
   , ALTER_TRIGGER
   , DROP_TRIGGER
AS
   SET NOCOUNT ON ;   
   Declare @UserName varchar(50) = lower(SUSER_SNAME())
   Declare @ServerName varchar(50) = @@ServerName
   Declare @DatabaseName varchar(50) = DB_Name()
   IF lower(UserName) NOT IN
      (
         lower('foo\bar')
         , lower('foo\baz')
         , lower('foo\qux')
      )
   BEGIN
      IF EVENTDATA().value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(50)') LIKE
            '%CREATE%'
      BEGIN
         RAISERROR('you are not allowed to add', 18, 1);
         ROLLBACK;
      END;
      
      IF EVENTDATA().value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(50)') LIKE
            '%DROP%'
      BEGIN
         RAISERROR('the %s server cannot drop', 18, 1, @ServerName);
         ROLLBACK;
      END;
      
      IF EVENTDATA().value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(50)') LIKE
            '%ALTER%'
      BEGIN
         RAISERROR('no alters at %s database', 18, 1, @DatabaseName);
         ROLLBACK;
      END;
   END;
GO
ENABLE TRIGGER [block_changes] ON DATABASE
GO

 
 

I thought it was cool. I've "cleaned" it up in my own goofy way. I included the @ServerName and @DatabaseName variables just because he had them and I thought they were cool too. Um, obviously you can just turn this trigger off in SSMS at "Database Triggers" under "Programmability" under the database under "Databases" under the server, but... well, again, it's cool.

RAID log

RAID is Risks, Assumptions, Issues and Dependencies in this setting and the log itself can just be an Excel sheet honestly. This is project management basics.

Sunday, August 18, 2019

CS is computer science

four semesters of calculus, etc.

a simple example of an Entity Framework update

This is stolen from this.

using (var context = new SchoolDBEntities())
{
   var std = context.Students.First<Student>();
   std.FirstName = "Steve";
   context.SaveChanges();
}

 
 

Note that we are not attaching or adding the student to the context, not in this case.

There seems to a safeguard in the form of an "Are you sure?" message to keep you from accidentally dragging a file from one folder to another at the Solution Explorer in Visual Studio 2019 nowadays.

This is overdue. It does not seem to work cross-project however. I wish Visual Studio was smart enough to just stop Kestrel whenever I start typing in a class whenever it is running in lieu of telling me that I can't change the code while the debugger is underway. I hate that too.

Friday, August 16, 2019

Hedera Hashgraph

This kind of builds on the blockchain idea and has some security safeguards.

analysis paralysis

It's when you cannot go forward because you are thinking about the challenge ahead too hard, imagining terrible hypotheticals, agonizing over what might be, etc.

How do I get the name of the browser from the IHttpContextAccessor?

Following up on this, you can do something like this:

string browser = _accessor.HttpContext.Request.Headers["User-Agent"].ToString();

 
 

How well does this work? Well, I can get back some gunk that tells me if I am using Chrome which looks different than the gunk that comes back from Internet Explorer. However, the gunk that comes back for Internet Explorer doesn't say IE in it anywhere, so that is kinda lame. Sabina Spielrein might stress.

NullInjectorError: No provider for FormBuilder!

ReactiveFormsModule needs to go in the imports of the module governing the component where this error occurs in an Angular app to make this error go away. Loop that in like so:

import { ReactiveFormsModule } from '@angular/forms';

I am probably not cut out to be a male model.

Nonetheless I wanted to share a recreation of a set of five Facebook posts I made this week every day before work.

1of5: The first of five new skinnier ensembles this week. Alright I've had the underarmor shoes for a couple of months now but they are still new and pristine. One of the outfits will use my old black and white Hawaiian shirt now that I can fit back into it so maybe that is cheating too. Everything else is new. This Hawaiian shirt comes from the gift shop at the Microsoft Visitor's Center in Redmond, Washington. The belt is Tommy Bahama. The trousers are Brooks Brothers.

2of5: Here is the preexisting Hawaiian shirt I eluded to in the last post. I got it from a street-side vendor on Austin's 6th street in either 2014 or 2015. It's probably my favorite shirt but I haven't been able to wear it in recent years as I've had to sport XXL stuff in lieu of XL stuff. The pants are Banana Republic. The shoes and belt are what they were in the last blog posting.

3of5: Good golly, today is really happy 1940s picnic day! Yes, I'm really going to work like this. The hat and umbrella weren't originally going to be a part of the ensemble but I picked them up in the Mall of America yesterday feeling flamboyant. The umbrella is from Old Navy and the hat from a shop called Chapel Hats with "Bailey" as the brand inside. The shirt is Tommy Bahama and the shoes and belt are what they were in the past two posts. The white trousers come from Banana Republic and its going to be a challenge keeping them clean. There was already a coffee mishap this morning where flecks of coffee got on them. I tried to clean up and I feel the lingering damage is so subtle that I might as well charge forward. I guess when I wash the pants they must get washed alone.

4of5: Conservative Thursday. Pants by Banana Republic. Shirt by Brooks Brothers. The belt and shoes are what they have been in the past three posts.

5of5: Here we are at the end of this. The shoes are what they always have been across all five posts and everything else in the outfit is Tommy Bahama. In another circumstance I might have to muster bravery to wear lavender slacks but not after Wednesday's ensemble, no. Bye all.

Thursday, August 15, 2019

How do I redeploy changes Octopus variables when rolling out a previous release.

Down the left side where is says: Overview, Process, Variables, Triggers, Channels, Releases, and Settings ...click on Releases and then find your release and click on its light blue number. Click the three dots at the upper right in a vertical line to open up a menu that has Edit, Prevent Progression, Update Variables, and Audit Trail. Click "Update Variables" here and then redeploy the old deployment as you normally would.

What survives a trip over the wire to a C# Controller from Http calls in Angular apps.

Assuming this example (for example), I used to think formData had to be JSON object as a string certainly didn't survive, but that is not so. An integer can make its way across too. I'd imagine other simple primates can be shepherded across.

How do I hand a nullable value into a stored procedure as a parameter from the C# side?

This won't work:

public List<DivisionStatus> GetDivisionsByCds(int? reportId, string connectionString)
{
   var sqlParameter = new SqlParameter()
   {
      SqlDbType = SqlDbType.Int,
      ParameterName = "@CFTCReportID",
      Value = reportId
   };

 
 

This will:

public List<DivisionStatus> GetDivisionsByCds(int? reportId, string connectionString)
{
   var sqlParameter = new SqlParameter()
   {
      SqlDbType = SqlDbType.Int,
      ParameterName = "@CFTCReportID"
   };
   if (reportId == null)
   {
      sqlParameter.Value = DBNull.Value;
   }
   else
   {
      sqlParameter.Value = reportId;
   }

 
 

This could kinda be a sister blog posting to this.

Automattic, parent of Wordpress.com, will own Tumblr.

Verizon doesn't want it anymore for some reason. Imagine that!

PID is going to stand for ProcessID.

See this. This came up randomly today. Oh, and, ID stands for Identifier (and maybe not Identification or Identity) if that is not obvious.

Wednesday, August 14, 2019

When you just push branches to master without doing "git pull" first...

...well, bad things happen don't they? Try not to get into this habit in the git paradigm. In Azure DevOps/Octopus CI orchestrations wherein a build number has to be manually incremented upon check in for every successful build this will in particular be a pain point when not getting the latest from master. You'll think you are incrementing the number when really someone else has already incremented the number to the same thing and already made their own commit.

a better version of the snipping tool

You may get Snip & Sketch from the Microsoft Store for free and it is a better version of the snipping tool. SnagIt is still yet better yet. I learned today that you keep a history of everything you screengrabbed with SnagIt!

A required parameter cannot follow an optional parameter.

When you see this error in TypeScript it is exactly what it appears to be. Move the optional parameters in your method/function signature farther downstream past the not-so-optional parameters and the problem will go away.

You probably should NOT try to scrape an IP address from a web site from Visual Studio project that is not the UI.

My various Sabina Spielrein flavored blog posts about finding yourself suggest as much but I was really wrong. I'm sorry.

If you try to dig up an IP address by a call tucked away to the infrastructure project of your application's onion architecture like it is an external dependency you are just going to get the IP address of the server running the app as best as I can gleam. I recommend getting the IP from the browser hitting a controller endpoint at the controller itself like so in .NET Core:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
namespace FluffyNothing.UserInterface.Controllers
{
   public class HomeController : Controller
   {
      private IHttpContextAccessor _accessor;
      
      public HomeController(IHttpContextAccessor accessor)
      {
         _accessor = accessor;
         _timekeeping = timekeeping;
      }
      
      public IActionResult Index()
      {
         var x = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();

 
 

There is not a Controller versus ApiController divide anymore as of MVC 6 and thus this trick will work with ReST calls too. There are however two other things you may see which may trouble you:

  1. ::1 which is what you are going to have for an IP when you run locally and this stumbling point is exactly the sort of thing that took my down the wrong rabbit hole wherein I was scrapping IP addresses from websites at the outside. When you spin up a server at Rackspace and actually run stuff there it will behave differently than when you run Kestrel out of Visual Studio 2019. I promise.
     
  2. Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'MyApp.UserInterface.Controllers.HomeController'. ...which means that in the IoC stuff in Startup.cs you will need:
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Now I feel better about me:

HTTP Error 502.5 - ANCM Out-Of-Process Startup Failure

This had a way around this error. It suggests, that after you install .NET Core that you should run these commands from the command prompt back to back and it's not wrong.

  • net stop was /y
  • net start w3svc

Oh, also permission IIS_IUSRS user to interact with your site in IIS as well. That is important too. Right-click on the site in Internet Information Servies (IIS) Manager and pick "Edit Permissions..." to get the dialog box with with General, Sharing, Security, Previous Versions, and Customize tabs across the top. At the "Security" tab assign better permissions to IIS_IUSRS.

Tuesday, August 13, 2019

Unhide file extensions at Windows Server 2012 R2!

It's the same thing as this.

Set up IIS on Windows Server 2018 R2.

Basically, follow these steps and pick "Role-based or feature-based installation" at "Installation Type" step of the wizard. Under "Server Roles" at "Select server roles" there will be a checkbox for "Web Server (IIS)" to check. Finish up the wizard. Another way to get there is to open the control panel and then go to "Programs" and then "Programs and Features" and finally "Turn Windows features on or off" is what you want to click. Anyhow, IIS should now appear as fifth item at the "Server Manager" as expected. To get .NET Core afloat run the installer at https://dotnet.microsoft.com/download/thank-you/dotnet-runtime-2.2.6-windows-hosting-bundle-installer as alluded to at https://docs.microsoft.com/en-us/aspnet/core/tutorials/publish-to-iis?view=aspnetcore-2.2&tabs=visual-studio ...in much the same way I have had trouble with affect versus effect, I have had trouble with allude versus elude. The former means to point to something indirectly and the other means to run/hide/escape.

Monday, August 12, 2019

Docker versus Octopus

A coworker suggests that the point of a container like Docker is that as it gets promoted up to different environments that the application inside keeps permissions set environment-to-environment without heartache. Where I work there is plenty of pain environment-to-environment with Octopus rollouts, but once you get on the other side of the environmental horror you generally tend to be all set and then it tends to be clear sailing. So is Docker overkill?

You'd better install ReSharper as the same user that you run Visual Studio 2019 with.

This comes up at my work as we have to use a different user other than the one we log into Windows with to do anything as Administrator. As best as I can tell the trial will start fresh if you install ReSharper as a different user which blows my mind. On my home machine what is stopping me from just making a different user every month and never paying for ReSharper?

The J in IntelliJ is going to stand for Java.

(not JavaScript)

What is the difference between the Standard and Web versions of SQL Server is the last few versions?

It has to do with the maximum memory size of a database and the number of cores in multithreading. Standard is a bit better and more robust I suppose. This has a cheatsheet.

Sunday, August 11, 2019

an example of getting something back asynchronously from an XHR in JavaScript

var homepageEvent = function(response) {
   if (response) {
      if (response.currentTarget) {
         if (response.currentTarget.response) {
            var mainstay = JSON.parse(response.currentTarget.response);
            if (mainstay.currentPlayer) {
               if (mainstay.currentPlayer.playerIp) {
                  var layout = document.getElementById('layout');
                  var links = document.getElementById('links');
                  var summary = document.getElementById('summary');
                  if (mainstay.existingGame) {
                     summary.innerHTML = "Alright " + mainstay.currentPlayer.playerIp + ", you
                           are in a game!";
                  } else {
                     layout.style.display = "block";
                     links.style.display = "block";
                     summary.innerHTML = "Welcome " + mainstay.currentPlayer.playerIp + "!
                           Would you care to play?";
                  }
               }
            }
         }
      }
   }
};
var homepageAjax = function (url) {
   var homepageXhr = new XMLHttpRequest();
   homepageXhr.addEventListener("load", homepageEvent);
   homepageXhr.open("GET", url, true);
   homepageXhr.send();
};
function PrepHomePage() {
   homepageAjax('/api/values');
}

You can probably skip the FormBuilder in an Angular application.

"ASP.NET Core 2 and Angular 5" by Valerio De Sanctis shows us FormBuilder as a wrapper of syntaxic sugar around a FormGroup in the reactive forms stuff that allows for interfacing with say .setValue on the FormGroup. There will be a .group hanging off of the FormBuilder which is the FromGroup it wraps.

Friday, August 9, 2019

deepfake

This is the art of altering, augmenting, and even replacing a face in one video clip with the face in another video clip. Artificial intelligence is in the mix to make this happen!

There is a skybridge maze in downtown Minneapolis.

Femi Oyekan once told me back in Texas that you can walk all around the downtown of Minneapolis in skybridges and that they have to have something like that there because it gets so cold. I have lived in the Twin Cities for a year now, but only today ventured into the skybridge maze as I really don't have a reason to go to Minneapolis and moreover you have to go on a weekday during work hours or the skybridges will be closed. As it happens, today is the last day of my first week off in three* years and I knew what I wanted to see today. It looks like so:

When I visited The Software Guild eight days ago, I realized that their building was on the skybridge system so I went in there to begin with and then up to the second floor where the vast majority of the skybridge infrastructure sits. As I wandered building to building, I found places to eat and department stores! I did manage to get lost too. Fun!

*I suppose I had a full week off just shy of two years ago if you count some of the bonus time Hurricane Harvey logistics added to my California trip by making it impossible to fly back to Houston.

indices in C# 8

You may get a range from an array in C# 8. To do so you may specify numbers of an Index type (use Index instead of int as the type) and then, instead of normally pulling out a single item by a number in square brackets, instead have foo..bar in the square brackets wherein foo and bar are examples of indices. Leading a single number with the hat operator (a carat) in the square braces will find the actor at a position equal to the length of the array minus your number. For more on new array manipulations see: this

television and restaurants

I do not own a TV but on the way back from this road trip, I saw at bit of the August 7th broadcast of "The Late Show with James Corden" on the TV at the Finlen Hotel and Motor Inn in Butte, Montana. The guests were Joel McHale and Betty Gilpin. The conversation seemed to have to do with getting high with Joel McHale speaking to how he once got high off a pressurized can of whip cream. This was an easy out for him in an awkward conversation. Betty Gilpin in contrast more candidly mentioned that when she was a waitress before making it as an actress that she showed up to work on marijuana every day and once gave a guest ChapStick when they asked for chopsticks.

I think her story is stereotypical of that of a lot of young people struggling with jobs they hate in their twenties. I have run into so many characters waiting tables who are kinda stuck waiting tables and not able to climb the ladder in life. What is more, their "self-medicating" is keeping them where they are.

tag cloud

It is the name for that goofy layout of a bunch of words to describe something is a visual blob with the bigger words carrying more weight than the smaller ones but wherein all of the words do contribute to thoughts about the thing in question.

I took a trip to Seattle.

I went up in the space needle, saw this tech talk, and, yes, visited Pike Place Market where I saw some fish. Both photos here are from 8/5/2019 and the one above is of one of "The Spheres" in Seattle which are Amazon-owned greenhouses. I also went in one of the Amazon Go convenience stores where you may only pay with your Amazon account. The photo below cheats a bit because it was technically taken in Redmond, Washington and not Seattle, Washington. It was taken at the Microsoft Visitor Center and the visitor seen here seems transfixed by a screen in a gaming room themed around Minecraft.

How do I host a .NET Core web site in IIS?

This suggests that IIS will run Kestrel as a reverse proxy and also explains how to skip a pass through from one to the other with "in process hosting" with the 2.2 stuff. This suggests that with either Windows Server 2008 R2 or Windows 7 or something up the ladder from those two, more modern, that you should be good to go in Windowsland.

I saw John Baluka speak on nopCommerce on Tuesday night.

This was a monthly meeting of a Seattle, Washington .NET User Group called ".NET Developers Association – Westside" and Parametric was the host. Parametric does software for managing investments and is located in one of the skyscrapers in Seattle. nopCommerce (nop rhymes with cop and is not no op) is basically just some open source .NET application that you may pull from GitHub or even Subversion somehow and customize/reskin and then use as your own for your storefront. You have to pay a thousand dollar fee to remove the "Powered by nopCommerce" logo so most people just leave it there. Otherwise there is no fee to pay to use it. Andrei Mazulnitsyn the creator makes his money in selling nopCommerce-favored consulting in a business model much akin to the one Udi Dahan used to run before NServiceBus stopped being free and John Baluka for that matter does the same thing only he is based in St. Louis and courts American clientele while Andrei and his team are in Russia. nopCommerce is a rival really to Shopify, Salesforce's own solutions for eCommerce, Magneto, WooCommerce for WordPress, and also, amongst others, two other open source .NET solutions in the space, one of them being smartstore.net which is a fork of nopCommerce and the other being VirtoCommerce which uses Elasticsearch under the covers and AngularJS at the front end. You may use Visual Studio Dev Essentials (a lighter version of the Visual Studio IDE) to work on nopCommerce. nopCommerce uses Autofac for the dependency injection variant of inversion of control. There is a DependencyRegistrar.cs file in one of the projects that has all of the wire-ups and the app will not compile if a dependency is missing. We didn't dig too deep into how the plugins work, but apparently you may loop in a plugin without recompiling the code base! There is a marketplace for plugins. Nop-Templates is a company that offers a plugin that exposes a ReST API for doing various things with nopCommerce. I guess you could use this to put an Angular or React frontend atop the app in lieu of using the default Razor stuff. The default Razor stuff is responsive (mobile-friendly). nopCommerce has had a long life and didn't start out as of MVC in .NET Core but it is there now. The first time you run nopCommerce you get a little form wherein you punch in stuff like what the database is and where it is at, how to get at it. Entity Framework is used under the hood and there is some infrastructure to make it eventually swappable with a different technology. Nothing gets truly deleted in the nopCommerce system and instead a flag is set at a database column to denote a pseudodeletion. AutoMapper is in the mix. The unit tests are in NUnit and you need the NUnit Test Adapter to work with this stuff. Other things mentioned in this talk included Flutter which is something like Kotlin for the Go stack in the mobile space. IBM i is an operating system that runs IBM gunk. Interop is short for interoperability or interoperable and it is characteristic of exposing interfaces for outside actors to interact with in the name of ease of cross talking to the thing in question. TestStack is something like Selenium for testing WinForms and WPF and both things fall under the umbrella of functional testing as opposed to integration testing or unit testing. BuiltWith.com will let you type in a technology like nopCommerce and it can tell you what the rivals are in the space. Moreover, if you just punch in a website's URL it will tell you, as best as it can gauge, what technologies were used in making the site. Your Pluralsight profile has a public facing URL and you may just hand this to someone you are interviewing with in the name of answering the "What do you do to keep up with industry trends?" interview question as the URL will reveal all of the Pluralsight trainings you have watched. BizSpark, as a program, used to let you buy three years of an MSDN (Microsoft Developer Network) license. John is working on a POC (proof of concept) for nopBlazor which is going to be a Blazor-with-nopCommerce solution as the name implies.

Katas

A kata is a movement made to be repeated over and over as practice in Japan. In American geek life these are little affirmations you say to yourself over and over or things you repeat to yourself to make you a better worker.

Saturday, August 3, 2019

I saw Brett Hazen speak on Azure Durable Functions on Thursday night.

This was a meeting of the Twin Cities .NET User Group, but it was not at the usual locale. The Software Guild in downtown Minneapolis instead served as the venue for the talk and they are a coding academy. Azure Durable Functions extend Azure Functions and make them less likely to fail. Brett gave the example of the validation of a multiline report with Azure Functions, how it could be painful, and how the pain could be alleviated with Azure Durable Functions. Imagine if the report is broken into individual lines by one function, a function is called for each line for validation, and then the lines are then aggregated back into a report. (This is the Fan-in, Fan-out pattern.) The last step is tricky if the individual line validations are happening asynchronously instead of sequentially, right? How do you keep track of what is done and undone? Azure Durable Functions allow you to use state without a database to solve this problem. Azure Functions let you use C#, F#, JavaScript, Java, and Python and Azure Durable Functions let you use the first three of these. With the first two you may use precompiled libraries. A "trigger" entry point kicks off a Durable Function, typically an HTTP call. The trigger points to a "client" which is in C# a method which may take a few things at its signature, but amongst them always is an "orchestrator" which is deterministic, giving consistent results every time for given inputs unpolluted by any wildcard that could corrupt that such as temporary data or the time of day. DurableOrchestrationContext is the C# type for the orchestrator and the prose going forward will assume C#. It was, after all, a .NET talk. One thing to say about JavaScript is that you cannot use the async and await keywords in a client, but C# in contrast invites a pattern wherein you will hit checkpoints in a client whilst awaiting at the await keyword and these write a bunch of events to an event store. Event Sourcing is a pattern for such a store with its own history of what happened and where you are at and this allows a client to fail midstream and be recovered in such a manner that it can pick back up where it left off. Such explains the use of the word "durable" in the moniker Azure Durable Functions. Brett projected some of the tables used in Azure Storage Explorer which looked a lot like SSMS to me. In think HubInstances and HubHistory are the tables to really care about herein with HubHistory holding the event records. If you want to store your own data in some cloud tables too you should really provision your own account. It will cost you pennies to host the data as long as you aren't doing something really crazy and nothing to split off a second account. Orchestrations should be nonblocking. The Durable Functions Framework is built on top the Durable Thread Framework which is single-threaded. Control queues help you scale things out but you'll likely never use these directly. 64K is the limit for the average message size in Azure's messaging queue. Use try/catches to do error handling. Newtonsoft's Json.NET does serialization. Be wary of attempting to serialize the unserializable which in C# kinda means objects which have more than zero constructors yet zero constructors which take zero variables at their signatures. If the constructor expects something the object it is going to blow up when you serialize it. Microsoft.Azure.Functions.Extensions when looped in as a NuGet package allows for inversion of control. You may use singletons and transients (not singleton, created anew when called every time). Some things like Thread.Sleep can really throw a wrench in the works (avoid!) and, as I've mentioned in the name of being deterministic, you really can't use the clock. Off of your instance of DurableOrchestrationContext, probably called context, is a .CurrentUtcDateTime and a .CreateTimer for this sort of stuff to be used instead. The context also has some convenience URLs that may be exposed and called for other manipulations. For scenarios in which you wait for a day for an approver to maybe approve something, by way of a convenience URL, and then fall over to plan B when a day has elapsed, you will need to call a cancellation token on the timer when the approver does approve to clean it up. When you change your client how will you alleviate the pain of the rollout side-by-side with previous running versions? You could do nothing, stop everything in-flight, or roll out a brand new application. Brett prefers a watered-down version of the third way to go wherein you just have a new method with the version number directly in its name in the same application. External Orchestrations allow for infinite loops which should be avoided in regular orchestrations. You may have suborchestrations to break up what could become a big procedural mess in a client. There is the concept of Concurrency Throttling to manage how many instances of a client may run at once. You may mock a DurableOrchestrationContext with MOQ to unit test a client. Other things mentioned at this talk included Windows CE (which is Windows Embedded Compact or WinCE), an operating system for embedded devices, and the fact that Robert Martin (Uncle Bob) was the founder of Agile which I had not heard before. Shadow IT is any sort of app spun up at work outside of the permissions of the higher-ups and the blessing of the corporate entity via the proxy of higher-ups. IT here is for information technology just as you'd expect. Other things mentioned at this talk by Brett Hazen himself include Insomnia which is something like Postman, Azure Service Bus for SOA, and CsvHelper for CSV stuff. Polly lets you retry/rerun HTTP calls.

Friday, August 2, 2019

If you want MOQ to return null for a mocked method you have to cast null to the specific type otherwise returned.

.Returns(null);

 
 

...must instead become:

.Returns((YourTypeHere)null);

A button should be an actionable item and a link for merely going somewhere and viewing something.

That's good UX!

phData

They are a company that offers big data solutions.

You may make a "Related" association between two stories in Azure DevOps.

This is not a parent/child relationship of a story and a task. Instead, two stories may have a one-to-one sisterhood by way of being deemed related. Maybe one-to-one is a stretch as I'm sure a story can be related to more than one other story.

ETL two-step

When drinking up data from numerous sources to a landing database and then transforming the diversified data into a common format that lives in a second database, the landing tables should probably keep the table and column names of their sources in other systems. There are tools that will make the autodiscovery of what feeds what reverseengineerable if you don't confuse things with a name change.

Photoshop Document is what .psd stands for.

Graphics Interchange Format if what .gif stands for and .jpeg (often just .jpg) is Joint Photographic Experts Group.

Thursday, August 1, 2019

How do I test with Postman the endpoints of an API that an Angular application rides atop while using ADAL for the authentication?

If you just hit the endpoints you'll get errors indicating that you're unauthenticated, right? Well, you can browse the app normally just enough to get the token in the URL line of the browser and then hand that token in to API calls as a header with Postman. That is the workaround for this. Even if you redirect after getting the token in the app, from any one "page" that's not superficial you should be able to look at the API calls in the Network tab of Google Chrome Developer Tools and drill into one of the API calls to get at the token.

Failed API calls out from an Angular app will appear in red at the Network tab of Google Chrome Developer Tools.

You may click on the red items to see the specific messages.

iTextSharp

You make PDFs with it, maybe in an Angular application, maybe from C#. As of version five it uses the AGPL license (GNU Affero General Public License) and that means you have to publish and code that uses it or else pay a license fee. Affero Inc. was a web development business in 2001. In Latin the word means bring/give/apply etc.

SAP Enable Now

This really doesn't have much to do with SAP the software. This allows you to record the screen to make a training presentation. It has some features to records exactly what is being clicked in a manner more robust that other comparable tool.

Deskside support is akin to desktop support.

I had not heard the term deskside before today.

Fifth Edition

1974, the year I was born, was the first year of punk rock, home computers, and, yes, D&D. As of 2014 there is now a 5th edition of Dungeons & Dragons. I am playing in a campaign with it now. Tyranny of Dragons is the campaign. I'm guessing Tiamat herself will be the end boss to fight. This is my first attempt at gaming in like nine years. I modeled a barbarian character around this plastic miniature: