Posts

Review: Rock Your Code: Defensive Programming for Microsoft .NET by David McCarter

Image
I saw a post on Twitter from a guy named David McCarter  promoting his new book.  Rock Your Code: Defensive Programming for Microsoft .NET . I thought the title looked interesting so I bought it. This book (if approximately 50 pages of A5 can count as a book) was packed with bad advice. It is going to be more effort to explain why than the book deserves, but I will do it. TL;DR Source code doesn't compile. When it does, it doesn't do what the author says it does. The author promotes practices long established as poor. Chapter 1: OOP This chapter explains the three pillars of OOP are Encapsulation, Inheritance, and Polymorphism. The author has a tiny 1 or 2 sentence explanation of each. He then goes on to show an example of some poor source code "from a real in production project" (I hope he has permission from the copyright holder). The source code is a single class with lots of public attributes. That's the end of the chapter. Honestly, th

Assigning a piped async result to a variable in an Angular view

If you have an Observable<x> in your component you might find yourself doing something like this {{ ( source$ | async)?.property1 }} {{ ( source$ | async)?.property2 }} This will subscribe to the source$ observable more than once. A commonly used technique to avoid this is to assign the result of the async into a view variable, like so: <ng-container ngif="source$ | async as source">   {{ source?.property1 }}   {{ source?.property2 }} </ng-container> But if you have other UI elements within that ng-container that you want to be displayed whether or not source$ has emitted a value then you might not like the fact that a portion of your UI is excluded until the observable emits a value or when the observable emits a falsey value. If that is the cast, you can try this little trick. <ng-container ngif="(source$ | async) || {} as source">   {{ source.property1 }}   {{ source.property2 }} </ng-container> We utilise *ngIf to a

Implementing a really simple Elvis Operator in TypeScript

Here is a simple routine that implements what is known as the Elvis Operator in TypeScript. In C# you can write code like this Nullable<int> age = person?.BestFriend?.Mother?.CurrentHusband?.Age); If any of the values along the way it will return a null rather than throwing a NullReferenceException. Using the class in my previous blog  Get a Lambda expression as a string  it is possible to achieve the same in TypeScript using the following format const age = elvisOperator(person, x => x.bestFriend.mother.currentHusband.age; It doesn't currently support anything more than simple property access, so you can't access elements in an array for example. import { Expression } from './expression'; export function isUndefinedOrNull(value: any): boolean { return _.isNull(value) || _.isUndefined(value); } export function elvisOperator (instance: TSource, member: (v: TSource) => TResult): any { let path = Expression.pathAsArray(member); let result

A type safe way of creating Angular ReactiveForms and FormGroups

If, like myself, you prefer as many of your coding mistakes to be identified at compile time as possible then you might like the following example. The FormBuilder in Angular expects us to identify our FormControls with a string name. If ever the API of your server changes then of course the names of those controls will also need to change. So, rather than using magic strings when building a FormGroup I wrote this small utility class for building them against a strongly typed class by using lambda expressions. This routine uses a routine I blogged about recently  ( Get lambda expression as a string) Take the following interface as an example of something we wish to edit in a ReactiveForm. interface Address { line1: string; line2: string; city: string; } The code to build the form would look like this this.form = this.expressionFormBuilder .createFormGroup<Address>() .addFormControl(x => x.line1) .addFormControl(x => x.line2) .addFormControl(x

Failed to execute 'send' on 'XMLHttpRequest': Failed to load ng:///DynamicTestModule - Solved (Angular testing)

If when you run your tests you see an error similar to this Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'ng:///DynamicTestModule/xxxxxxComponent_Host.ngfactory.js It means something in your component is throwing an exception and the test framework is returning a wrapped exception. To see the actual exception run ng test with -sm=false as a parameter ng test -sm=false This will not only stop your browser from freezing on that test, but will also give you the original error including line number.

Angular - How to create a data aware custom component

Introduction This blog will demonstrate how to create an Angular component that you are able to add [ngModel] [formControl] and [formControlName] attributes to your custom component, and have your component correct implement the features required to work with Angular forms. Setting up the ngModule First add FormsModule and ReactiveFormsModule to your main NgModule's import declaration import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Creating the custom component's template Note: If you have installed @angular/cli using npm you can type ng g component /components/custom-input in a command prompt to create the component + template + test cases. Next create a new component with the following html template My custom input <input (

TypeScript - A polyfill to extend the Object class to add a values property to complement the keys property

I expect you've used Object.keys at some point. Here is how to extend the Object class to add a values property. This kind of thing is useful when you have a lookup of keys where all of the values are the same type, such as the following object you'd expect to see in a Redux app. { "gb": { code: "gb", name: "Great Britain" }, "us": { code: "us", name: "United States" } } The code interface ObjectConstructor { values<T>(source: any): T[]; } /** * Extends the Object class to convert a name:value object to an array of value * @param source * @returns {T[]} */ Object.values = function<T>(source: any): T[] { const result = Object.keys(source) .map(x => source[x]); return result; }

TypeScript - Get a Lambda expression as a string

One of the things I really like about C# is the ability to convert a lambda into a string. It's useful for doing all kinds of things, especially when you are calling a 3rd party library's method that expects a string identifying a member of an object. I saw this was lacking in TypeScript, which was a pain because I wanted to make various parts of my Angular application more compile-time resilient to changes in the server's API model. Using the following code it is possible to take a call like this someObject.doSomething<Person>(x => x.firstName) From there we can get the name of the property referenced in the lamba expression. In fact it will return the entire path after the "x." abstract class Expression { private static readonly pathExtractor = new RegExp('return (.*);'); public static path<T>(name: (t: T) => any) { const match = Expression.pathExtractor.exec(name + ''); if (match == null) { throw new

Angular - How to create composite controls that work with formGroup/formGroupName and ReactiveForms

This blog post will show you how to create composite controls in AngularX that allow you to reuse them across your application using the formGroupName directive to data-bind them. We'll start off with a very basic component that uses a reactive form to edit a person and their address. Editing a person's name and address import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormGroup} from '@angular/forms'; @Component({ selector: 'app-root', template: './app.component.html', }) export class AppComponent implements OnInit { public form: FormGroup; constructor(private formBuilder: FormBuilder) {} ngOnInit(): void { this.form = this.formBuilder.group({ name: 'Person\'s name', address_line1: 'Address line 1', address_line2: 'Address line 2', }); } } <form novalidate [formGroup]="form"> <div> Name <input formControlName="nam

Redux sub-reducer pattern for complex / nested data structures

Image
I love the idea of the Redux pattern, the way all reducers are pure and predictable. I love the way they are effectively listeners that act on event notifications received from a central dispatcher, and I really like the way the whole approach simplifies the application and makes code in my Angular app's components only concerned with view related concerns rather than business logic. However, what I am not a big fan of is the normalised data approach. I've seen it recommended so many times for use with the Redux approach. You essentially have any object (read "row from table on server") in memory once and then everywhere else you hold a reference to the locally stored record/object by its unique ID. So, a view state you receive that looks like this [ { "id": "Emp1024", "name": "Peter Morris", "address": { "id": "123", "street": "xxx" } }, { "id": "Emp4096&qu

Loading an assembly from a specific path, including all sub dependencies

public static class AssemblyLoader { private static readonly ConcurrentDictionary<string, bool> AssemblyDirectories = new ConcurrentDictionary<string, bool>(); static AssemblyLoader() { AssemblyDirectories[GetExecutingAssemblyDirectory()] = true; AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly; } public static Assembly LoadWithDependencies(string assemblyPath) { AssemblyDirectories[Path.GetDirectoryName(assemblyPath)] = true; return Assembly.LoadFile(assemblyPath); } private static Assembly ResolveAssembly(object sender, ResolveEventArgs args) { string dependentAssemblyName = args.Name.Split(’,’)[0] + ".dll"; List<string> directoriesToScan = AssemblyDirectories.Keys.ToList(); foreach (string directoryToScan in directoriesToScan) { string dependentAssemb

Running dotnet core xUnit tests on Visual Studio Team Services (VSTS)

Image
1: Run dotnet restore to restore package dependencies. 2: Run dotnet build to build the binaries. 3: Run dotnet test to run the tests. Note the additional parameters --no-build to prevent a rebuild and --logger "trx;LogFileName=tests-log.trx " to ensure the test results are written to disk, 5: Use  a Publish Test Results tasks to output the results of the tests. Make sure you set the following properties Test Result Format = VSTest Test Results Files = **/tests-log.trx And under the Advanced section make sure you set the Run This Task option so that it will run even if the previous task failed.

Get list of object keys in Angular

import { PipeTransform, Pipe } from "@angular/core"; @Pipe({ name: 'keys' }) export class KeysPipe implements PipeTransform {   transform(value, args:string[]) : any {     return Object.keys(value);   } } Then to get a list of errors for a form element you can do this <ul *ngIf="form.get('userName').invalid" class="help-block with-errors">    <li *ngFor="let error of form.get('userName').errors | keys">{{ error.key }}</li> </ul>

Preventing Unity3D IL2CPP from stripping your code

I was trying to get a list of a type's constructors at runtime using reflection, so that I could create an instance of the class using dependency injection. All worked just fine until we tried to build the app for iOS. At first we were using Mono as the scripting back-end, but it seems that new versions of iOS pop up a dialog telling the user the app is 32 bit and may run slowly (i.e. "Your app is crap"). When switching the backend scripting to IL2CPP (in File->Builder->Player Settings) the app suddenly wasn't working. It turns out that SomeType.GetConstructors().Count was returning zero, which was a problem because obviously I wanted to invoke those constructors with dependencies. The problem was that because these constructors weren't being calling explicitly from anywhere in my app IL2CPP decided I didn't need them, and stripped them out. The solution is to create a file in your Assets folder called link.xml and fill it in like so.... <lin

Forcing a device-orientation per scene in Unity3D

Unity3D has a Screen class with an orientation property that allows you to force orientation in code, which lets you have different scenes with different orientations (useful in mini-games). this works fine for Android but crashes on iOS. The problem is the file UnityViewControllerBaseiOS.mm that gets generated during the build for iOS has an assert in it which inadvertently prevents this property from being used. It is possible to create a post-build class that runs after the iOS build files have been generated that can alter the generated code before you compile it in XCode. Just create a C# script named iOSScreenOrientationFix.cs and paste in the following code - adapted from  this Unity3D forum post . using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using System.IO; namespace Holovis { public class iOSScreenOrientationFix : MonoBehaviour { #if UNITY_CLOUD_BUILD // This method is added in the Advanced Features Settings on UCB // PostBuildProc

A UI thread dispatcher for Unity3D

I've recently been working on implementing an IHttpService that can work outside of a MonoBehaviour and call out to web services asynchronously. Rather than providing my IHttpService.JsonPost method with callbacks I decided to have it return a Promise, the code for which I took from this  Real Serious Games  GitHub repository. The problem is that when you use WebClient's async methods they call back the Complete events on the worker thread, so code like this won't work because you cannot manipulate UI from any thread other than the main one. httpService.JsonPost<MyInfo>(url)   .Then(myInfo => someTextUiObject.text = myInfo.Name); And there seems to be no kind of thread Dispatcher in Unity3D for UI updates as there is in Windows.Forms - so I wrote my own. using System.Collections; using System; using System.Threading; using System.Collections.Generic; using UnityEngine; public class UiThreadDispatcher : Singleton<MonoBehaviour> {     static volatil

NodeJS, Web-Express, and TypeScript from scratch

Over the past year I've been spending my time contracting for a company in Norway. Now that project is completed it is time for me to start playing again, so I thought I'd pick up an old Node Express project. This time I intend to use TypeScript instead of Javascript. I'd also like to write unit tests and dependency injection - both are something I'm very familiar with in the C# world, but not in Node. I'm going to use this blog to record what I did; I will undoubtedly revisit some of these posts and make changes as I learn. In this first blog I intend to cover how to get up and running with Node, Express, and WebStorm (optional) from a fresh installation of Ubuntu Linux. The first thing we need to do is use apt-get to install Node. sudo apt-get install nodejs I've noticed that some Linux apps will look for a command "node" and others will look for "nodejs", so after installing I want to make an alias so that both commands

[Solved] MVCApplication Parser Error

I have this problem because I have to develop with VS running as administrator in order to use Local IIS hosting. When files are added (or generated by compiling) I think VS was setting the owner as Administrator, which IIS then cannot read. Start a command prompt as Administrator and type in the following icacls c : \devpath\yourwebsite / grant everyone :( OI )( CI ) F / T

How to Create a Self Signed Certificate in IIS 7

I know I am going to want this link again in the future!

VSTO Office plugin not appearing in Office 2007

If you have an office VSTO plugin that is working in other versions of Office but not appearing in Office 2007 then try setting the following registry value HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\12.0\Common\General\ Name = EnableLocalMachineVSTO Value (DWORD) = 1

Watching a single property in an array in AngularJS

A typescript example that converts the array's property into a single string that can be watched. $scope . $watch ( () => this . someArray . map ( x => x . selected ? "1" : "0" ). join ( "" ), ( newValue , oldValue , scope ) => this . onSelectionChanged ( this . getSelectedItems ()));

Getting an AngularJS directive to call back a method on its parent's controller

Here is a TypeScript example of how to call back a method on the controller from an embedded directive. The most important thing to note is that the directive's parameter name for your callback uses a & when defined, and when calling that callback you should not use positional parameters but instead use an object with properties having the names of the parameters in the target. Register the directive when you create your app module: module MyApp { var app : angular . IModule = angular . module ( "MyApp" ); MyApp . Directives . FileUploader . register ( app ); } The registration code is as follows: module MyApp . Directives . FileUploader { class FileUploaderDirective implements angular . IDirective { public restrict : string = "E" ; public templateUrl : string = "/app/Directives/FileUploader/FileUploaderDirective.html" ; //IMPORTANT - Use & to identify this as a method reference

AngularJs - binding HTML

The directive ng-bind will escape HTML to avoid data acting maliciously. If you want to output html you need to use ng-bind-html <div ng-bind-html="someHtmlBody"/> The important step to getting this working is to ensure the script angular-sanitize.js is referenced on your page, and it is specified as a dependency when creating a module.... var app = angular.module("MyApp", ["ngSanitize", "OtherDependencies"]);