Monthly Archives: December 2023

The IAM User on AWS

When you signed up for AWS you created a Root user account. However we really should create another user (even if they have root like permissions) to run our cloud account.

Why do we need this user if they’re basically admin? Well we can reduce permissions but also delete the user without affecting the root user which we cannot do this on.

Let’s create an IAM (Identify and Access Management) user for our development use which will basically have admin permissions but would not be the user we use four out applications, this is essentially a developer account.

How do we set up our development user?

  • Log into your AWS account as Root user
  • In this search bar type IAM
  • First we want to create a new group, so select Access management | User groups
    • Click Create group
    • Enter a name for the group, usually we’d probably have this name match the application that the group represents, so I’m going to do this for my unit conversion API app, hence my group is UnitConversionApiUsers for my unit conversions API
    • In the Attach permissions policies let’s give this group AdministratorAccess permissions
    • Now click the Create group button
  • You should be placed back on the User groups screen and see out new group with zero users. So now click the Access management | Users option on the left of the screen
    • Click the Create user button
    • Enter a name for the user then click Next
    • Leave the default Add user to group
    • Check/tick the group you added then click the Next button
    • Finally click Create user
  • From the users screen on the Security credentials tab I have also clicked Enable console access, I also check the User must create new password at next sign-in, but you can autogenerate or create a custom password to suite
  • Download the .csv file for later use, but don’t worry if you don’t it will contain User name, Password and Console sign-in URL so you can copy these if you prefer from the UI

Note that the console URL contains the account number, we can change this using the alias option, from the IAM dashboard select the Dashboard option. On the right of the screen you’ll see AWS Account and am option to Create an Account Alias, clicking this we can enter a name to replace the account number in the URL. You’ll see the Sign-in URL change to suit.

Try signing into AWS by using the console URL or it’s alias if you changed that and in my case I was prompted to change the password, so did that and was able to log in.

You’ll also want to go the the user that you created and click Create access key. When completed download the .csv and or copy the access id and secret key so you can used from the AWS CLI or IDE integration.

Collection Expressions in C# 12

C# 12 includes something called Collection Expressions. These offer more generic way to create our collections from array-like syntax.

Let’s look first at the old style creation of an array of integers

var array = new [] { 1, 2, 3 };

This is simple enough array is of type int[]?. This way of creation arrays is not going away, but what if we want to change the array to a different collection then we end up using collection initializers like this

var list = new List<int> { 1, 2, 3 };

There’s nothing much wrong with this, but essentially we’re sort of doing the same thing, just with different syntax.

Collection expressions now allow us to use syntax such as (below) to create our collection regardless of type

int[] array = [1, 2, 3 ];
List<int> list = [1, 2, 3 ];

On the surface this may not seem a big deal, but imagine you’ve a class that accepts an int[] and maybe you change the type to a List, passing the values via the collection expression [] syntax means that part of your code remains unchanged, it just remains as [1, 2, 3].

Along with this we get to use the spread operator .. for example

List<int> list = [1, 2, 3 ];
int[] array = [.. list];

In this example we’ve created a list then basically copied the items to the array, but a spread operator can be used to concatenate values (or collections), such as

int[] array = [-3, -2, -1, 0, .. list];

Creating your own collections to use collection expressions

For many of the original types, such as List<T> the collection expression code is built in. But newer collections and, if we want, our own collection can take advantage of this syntax by following a minimal set of rules.

All we need to do is create our collection type and add the CollectionBuilderAttribute to it like this

[CollectionBuilder(typeof(MyCollection), nameof(MyCollection.Create))]
public class MyCollection<T>
{
   // our code
}

Now this is not going to work, the typeof expects a non-generic type, so we create a simple non-generic version of this class to handle the creation of the generic version. Also notice the CollectionBuilder expects the name of the method to call and expects a method that takes a single parameter of type ReadOnlySpan and returns the collection type, now initialized, like this

public class MyCollection
{
  public static MyCollection<T> Create<T>(ReadOnlySpan<T> items)
  {
     // returns a MyCollection<T>
  }
}

Let’s look at potential bare minimum implementation of this collection type which can be used with the collection expression syntax. Notice we will also need to implement IEnumerable and/or IEnumerable<T>

[CollectionBuilder(typeof(MyCollection), nameof(MyCollection.Create))]
public class MyCollection<T> : IEnumerable<T>
{
  public static readonly MyCollection<T> Empty = new(Array.Empty<T>());

  private readonly List<T> _innerCollection;

  internal MyCollection(T[]? items)
  {
    _innerCollection = items == null ? new List<T>() : [..items];
  }

  public T this[int index] => _innerCollection[index];
  public IEnumerator<T> GetEnumerator() => _innerCollection.GetEnumerator();
  IEnumerator IEnumerable.GetEnumerator() => _innerCollection.GetEnumerator();
}

public class MyCollection
{
  public static MyCollection<T> Create<T>(ReadOnlySpan<T> items)
  {
    return items.IsEmpty ? 
      MyCollection<T>.Empty : 
      new MyCollection<T>(items.ToArray());
  }
}

Ofcourse this is a silly example as we’re not adding anything that the inner List<T> cannot supply, but you get the idea. Now we can use the collection expression syntax on our new collection type

MyCollection<int> collection = [1, 2, 6, 7];

Docker on Windows

Note: I’m going through draft posts that go back to 2014 and publishing where they still may have value. They may not be 100% upto date but better published late than never.

Up until recently I’ve been solely using Docker on Linux, but I’ve a need to use it with Windows now. I’ve installed Docker Desktop and set to Switch to Windows containers.

So first off we’re going to download a Windows image, whilst there are several variants, for server, nano windows, we’re going to go pretty much full blown using

docker pull mcr.microsoft.com/windows:2004

Note: It may take some time to download, it’s > 3GB

Now just to prove it worked let’s run it in interactive mode and starting the cmd prompt using

docker run -it mcr.microsoft.com/windows:2004 cmd.exe

Exit your image by typing exit followed by return.

I’m going to want to create a volume to save/share files with the Windows machine running the container, so let’s create a folder c:\shared and then copy or create a file in here, just to allow us to prove we can connect to it through the container, so mine’s predictably HelloWorld.txt, now run

docker run -it -v c:\shared:c:\shared mcr.microsoft.com/windows:2004 cmd.exe

Note: Change cmd.exe to powershell.exe if you prefer

I’m naming the folder in the image the same as the real machine’s folder, but you can change it to suit, just change the second path like this

docker run -it -v c:\shared:c:\shared2 mcr.microsoft.com/windows:2004 cmd.exe

and if you created a simple text file with a message in it, once we’re inside the container we can type

type HelloWorld.txt

from the c:\shared folder to see it it’s as expected.

Now I’m wanting to start to install applications into the container, but with no GUI we need “silent installs”

msiexec /i .\myapp.msi /QN /L*V install.log

C# interop with F#

Note: I’m going through draft posts that go back to 2014 and publishing where they still may have value. They may not be 100% upto date but better published late than never.

The intention of this post is to demonstrate how various bits of F# code are viewed from C# code. Obviously as both are .NET languages compiling to IL they can call one another’s code.

F# modules

Let’s start at the top, an F# module. So let’s look at a simple module

module MyModule

let squared x = x * x

The module will appears to C# as a static class and the function squared will become a static method, for example

public static class MyModule
{
  public static int squared(int x);
}

F# inferred the type to be an int

Ofcourse from C# we’ll call this function like any other static function

int result = MyModule.squared(4);

Null

The preference within F# is to use the Option type. But if you are working in C# and not wanting to include F# specific types you might prefer to still return a null. However if you are doing something like the following

match results with
| null -> null
| a -> new Thing(a)

This will fail to compiler with an error such as “The type ‘Thing’ does not have ‘null’ as a proper value.”

We can solve this by marking the Thing type with the attribute AllowNullLiteral, for example

[<AllowNullLiteral>]
type Thing() =
   // members etc.

or we might change the origina F# code to

match results with
| null -> Operators.Unchecked.defaultof<Scale>
| a -> new Thing(a)

Swift Protocols, Structs and Classes

Note: I’m going through draft posts that go back to 2014 and publishing where they still may have value. They may not be 100% upto date but better published late than never.

Introduction

Protocols can be thought of as similar to interfaces within languages such as C# and Java, hence are used to declare expectations for implementations and can be returned or accepted as params.

We declare a protocol in the following way

protocol Person {
  var firstName: String { get }
  var lastName: String { get }
  var age: Int { get }
}

So we can create our implementation of this procotol like this

struct PersonImpl : Person {
  var firstName: String
  var lastName: String
  var age: Int
}

Structs and Classes

Apple Swift developers seem to prefer value types over reference types, a struct is a value type and class a reference type. They both share many of the same functionality.

Structs do not require an initializer (constructor) as a default initializer is supplied automatically and will expect all non-optional properties to be supplied.

class PersonImpl : Person {
  var firstName: String
  var lastName: String
  var age: Int

  init(firstName: String, lastName: String, age: Int) {
    self.firstName = firstName
    self.lastName = lastName
    self.age = age
  }
}

As you can see, init is the name of the initializer or what we may view as a constructor. Classes may also have deinit is called when Swift deallocates an instance (struct’s do not have deinit).

Mutations

Where we expect changes to the internal data, in other words where a function mutates data we use the mutating keyword. If, for example, we add a protocol function

func incrementAge() -> Void // same as func incrementAge()

By default struct properties cannot be changed by instance method. In such cases we need to include the mutating key word, i.e.

mutating func incrementAge() -> Void

So a struct method implementation will now look like this

mutating func incrementAge() -> Void {
  age += 1
}

Within a class, we don’t need to mark the method as mutating.

Accessors

There are five access levels

  • Open: This allows proprties, methods, classes etc. to be accessible by anything that imports the module
  • Public: This allows proprties, methods, classes etc. to be accessible by anything that imports the module
  • Internal: This is the default access level and allows properties, methods, classes etc. to be accessible from the module where they’re defined only
  • Fileprivate: Properties and methods can access from code withint he same source file only
  • Private: The least visible accessor meaning properties methods etc. are only visible within the same file or class etc.

is and as

Swift has the concept of is and as pretty much like C#. So we can declare a type as follows

let p: Person = PersonImp("Scooby", "Doo", "12")

Now if we needed to check if the const p is a PersonImpl we would use

if p is PersonImpl {    
}

we could use as within the if statement if we wanted as well, for example

if let person = p as? PersonImpl {    
}

Here we compare and assign in the same line of code using as? which basically means the person may be nil (if the type cannot be converted to PersonImpl).

Extensions

Just like extension classes in C# – Swift extensions allow us to add functionality to structures, protocols and classes (as well as enumerations).

An extension is defined using the extension key word, for example

extension String {
  // add string functionality, for example
  func capitalize() -> String {
    return self[0].toUpper() + self.substr(1)
  }
}

We can also add constraints to extensions, so for example a Collection extension that

extension Collection where Iterator.Element: Comparable {
  // add functionality where elements support Comparable
}

Equatable

A type needs to conform to the Equatable protocol for a type to be comparable using == and !=.

Generics

Swift generics look much the same as generics in C++, Java and C# in that we can declare generics on a function like this

func add<T>(item: T) {
}

We can also add constraints to the genric type like this

func compare<T: Comparable>(a: T, b: T) -> Bool {
}

Experiments with Swift Generics

Note: I’m going through draft posts that go back to 2014 and publishing where they still may have value. They may not be 100% upto date but better published late than never.

Generics are interesting within Swift. Syntactically they look the same as most other languages which supports generics. So, we have the syntax below

class Policy<TResult> {
}

Generic and non-generic types of the same name

In C# we can essentially create a generic and non generic type and the compiler works out which we meant to use. Sadly this doesn’t exist in Swift (or Java or maybe many other implementations). But then, rather interestingly we can (assuming no constraint on the generic parameter) actually create a generic of type Void, i.e.

class Test<TResult> {
  func run(_ action: () -> TResult) -> TResult {
    return action()
  }
}

and then write code like this

let a1 = Test<String>()
let a2 = a1.run({ return "Hello" })

let b1 = Test<Void>()
let b2 = b1.run({ return })

What about, if we looked at this problem from the perspective of creating a default type for the generic. Swift doesn’t support this but we can (sort of) create something like this using init. Where we take an argument of the generic type, so for example if we have

class Test<T> {
  init(value: T) {
  }
}

Okay so we can now declare our variables like this

let t1 = Test(value: 42)
let t2 = Test(value: "Hello")

I know, this doesn’t have a default implementation at all, so instead we’ll create an extension which does the defaulting for us

extension Test where T == Person {
    convenience init() {
        self.init(value: Person())
    }
}

Now we create an instance like this

let t3 = Test()

See Can I assign a default type to generic type T in Swift? for further information on this one.

Adding constraints

We can add a constraint, for example the generic type must a a type of Error, like this

class Test<TError: Error> {
}

We can also create constraints against properties of a type, for example at a function level we can check or (as above) on extensions using the where clause. So in the example

extension Test where T == Person {
}

The extension implicitly knows that there’s a generic parameter T and so we don’t need to redeclare it, instead we’re simply saying this extension works for Test where T is a Person. This sort of technique can also be used within functions.

Default value

If you come from a C# background, you’ll probably be used to using default(T) or the shortened version simply default. Swift doesn’t include such a keyword. Instead you’ll either need to use optionals, i.e. returned a .some or .none, or ofcourse you might create a function of class to imitate such functionality yourself.

Swift async/await

Note: I’m going through draft posts that go back to 2014 and publishing where they still may have value. They may not be 100% upto date but better published late than never.

Swift comes with async/await syntax/functionality, however the support is dependent upon version of Swift and more importantly whether it’s the Mac (I’ll include iOS and watch OS in this) version of the Linux version.

Currently I’m playing with Swift on Linux and using the URLSession.shared.dataTask which is essentially a callback function. The URLSession.shared.data async/await version currently does not exist on Linux. So let’s create our own version and look at the process and ofcourse, how to use async/await (if you’ve used C#, TypeScript with async/await you’ll already know the basics of using the syntax).

Functions should be declared as async, so for example

func data(for request: URLRequest) async -> (Data, URLResponse) {
  // do something
}

Here’s an example of using the URLSession.shared.dataTask and declaring the code in an async method

#if canImport(FoundationNetworking)
public extension URLSession {
    func data(for request: URLRequest) async -> (Data, URLResponse) {
        await withCheckedContinuation { continuation in
            URLSession.shared.dataTask(with: request) { data, response, error in
                continuation.resume(returning: (data!, response!))
            }.resume()
        }
    }
}
#endif

Now, in usage, we can do this

let data = await URLSession.shared.data(for: request)

Currying and Partial applications in F#

Note: I’m going through draft posts that go back to 2014 and publishing where they still may have value. They may not be 100% upto date but better published late than never.

Currying

Currying leads to the ability to create partial applications.

Currying is the process of taking a function with more than one arguments and turning it into single argument functions, for example

let add a b = a + b

// becomes

let add a = 
    let add' b = 
        a + b
    add'

This results in a function syntax which looks like this

val add : a:int -> (int -> int)

The bracketed int -> int shows the function which takes an int and returns and int.

Partial Applications

A partial application is a way of creating functions which have some of their arguments supplied and thus creating new functions. For example in it’s simplest form we might have

let add a b = a + b

let partialAdd a = add a 42

So, nothing too exciting there but what we can also do is, if we supply the first n arguments as per the following example

let add a b = a + b

let partialAdd = add 42

notice how we’ve removed the arguments to partialAdd but we can call the function thus

partialAdd 10 
|> printfn "%d"

we’re still supplying an argument because the function being called (the add function) requires an extra argument. The partialAdd declaration creates a new function which is partially implemented.

By declaring functions so that the last element(s) are to be supplied by a calling function we can better combine and/reuse functions.

Structs and Classes in Swift

I’ve previously posted about structs and classes in Swift, let’s look a little more in depth into the subject

Differences between a struct and class

As you may know, structs use value semantics whilst classes use reference semantics. In other words if you do something like this

struct Point {
   var x: Double
   var y: Double
}

let pt1 = Point(x: 1, y: 10)
let pt2 = pt1

Your pt1.x, pt1.y values are copied to pt2.x, pt2.y. If you therefore alter p1 this does no affect p2. Swift using COW (copy on write) so this is more performant than one might think if you were making lots of copies – in other words the copying takes place only when a value is changed – so thing lazy copying of values.

Structs are stored on the stack and hence are very performant in terms of creation etc. Ofcourse if you’re making many changes to copies of a struct then things are less performant due to all the copying that needs to happen (even with COW).

Ofcourse, in a more complicated scenario, such as the Point also having a member variable which is a class, then these will be stored on the stack, but with references to the heap based classes. This is an issue for structs, if a struct contain multiple reference types it’ll incur reference counting for each reference type in the struct.

Classes on the other hand use reference semantics and therefore if we rewrite the about for a class. Then p2 is a reference to p1. Any changes to p1 will be reflected in p2

class Point {
   var x: Double
   var y: Double
}

let pt1 = Point(x: 1, y: 10)
let pt2 = pt1

Classes are stored on the heap which means that allocation will be les performant than a struct, but ofcourse if you’re passing around a reference to a class, this is more performant. However because a reference type copies the reference pointer it does ofcourse lend itself to issues around mutation of state and this becomes more of an issue when we add in concurrency.

The reference types use reference counting to handle auto-deletion (i.e. garbage collection). This does mean that a reference type will also require more space that a struct to track it’s reference counter. Also due to it using the heap, again potential concurrency issues means the OS must lock memory etc.

If you’re using String or the likes in a struct, you’re storing a reference type, hence this will incur reference counting overhead. If we’re using a String to ultimately represent known values, for example UP, DOWN, OUT_OF_SERVICE then not only will it be more type safe to use an enum, from a performance perspective this would be better, for example we can declare a status enum with a String type as a raw backing value like this

enum Status: String {
   case up = "UP"
   case down = "DOWN"
   case outOfService = "OUT_OF_SERVICE"
}

Late and Early binding polymorphism

I was taking part in an interview and was asked to explain “late and early binding polymorphism”.

Now I’ve programmed in C++, Java, C# and other OO languages for many years, but I’ve have never (that I can recall) heard of late or early binding polymorphism. Safe to say, I needed to find out more…

Early Binding Polymorphism

Early (also known as static) binding is when we override methods in subclasses, i.e. these are resolved at compile time.

So for example we have a Button which overrides the Click method and this is early or statically bound

public class Window
{
  public virtual void Click()
  {
     // handles a click on the window
  }
}

public class Button : Window
{
  public override void Click()
  {
    // handles a button click
  }
}

Late Binding Polymorphism

Late (also known as dynamic and runtime) binding is when we assign a derived type to it’s base type. So using the previous example code the following would cause late binding to take place, i.e. the virtual method Click is resolved at runtime.

Windows window = new Button();
window.Click();