Monthly Archives: September 2017

Short Walks – Using CompilerService Arguments in an Interface

Until today, I thought that the following code would work:

class Program
{
    static void Main(string[] args)
    {
        ITest test = new Test();
        test.Log("testing");
        Console.ReadLine();
    }
}
 
interface ITest
{
    void Log(string text, string function = "");
}
 
class Test : ITest
{
    public void Log(string text, [CallerMemberName] string function = "")
    {
        Console.WriteLine($"{function} : text");
    }
}

And, by work, I mean output something along the lines of:

Main : testing

However; it actually outputs:

: testing

CompilerServiceAttributes need to be on the Interface, and not on the implementation

class Program
{
    static void Main(string[] args)
    {
        ITest test = new Test();
        test.Log("testing");
        Console.ReadLine();
    }
}
 
interface ITest
{
    void Log(string text, [CallerMemberName] string function = "");
}
 
class Test : ITest
{
    public void Log(string text, string function = "")
    {
        Console.WriteLine($"{function} : text");
    }
}

Why?

When you think about it, it does kind of make sense. Because you’re calling against the interface, the compiler injected value needs to be there; if you took the interface out of the equation, then the attribute needs to be on the class.

You live and learn!

AutoRest

In the world of WCF and SOAP, if you want to consume a WCF service, you simply ask VS to add a service reference, direct it to the WSDL file, and it generates a client for you. Wouldn’t it be nice if you could do the same for a REST service!

It turns out that you can (although, admittedly, the process is not as seamless). The tool of choice for providing this WSDL emulation is called Swagger. This post isn’t about Swagger, and it assumes that you know your Swagger source. Azure has its own flavour of Swagger, called “Azure Swagger” (seriously). Consuming that is the main focus of this.

AutoRest

AutoRest is the client-side tool that allows you to automatically create proxy classes for your REST interactions, and is available via NuGet… but it doesn’t work at the time of writing this.

Instead, use Node Package Manager (NPM). First, install it, via this link.

Next, install AutoRest. Your friend here is the Package Manager Console:

npm install -g autorest

Update the version (this is, as I understand it, not strictly necassary, as it will install the latest version):

autorest --latest

Finally, check the version that is installed (okay, clearly this isn’t necessary at all, but I like to check that the computer and me both have a synchronised view of events as often as possible):

autorest --list-installed

Next, check where you are:

Then call AutoRest:

AutoRest -Input [SwaggerLocation] -Namespace [Namespace]

A note on Namespaces

It’s tempting to be dismissive of the namespace. Remember that, the namespace that you give will be assigned to classes and used by classes… so, if you were, for example, to give a namespace that matched the class name (so, for example, if you’re creating Recommendations, you’ll have a class called “Recommendations”) then you’ll find you’ll get thousands of strange errors that apparently make no sense. Think carefully about the namespace!

Where is the Swagger Location?

Obviously, the answer is, it depends… however; for Azure, most services have that readily available; let’s take Recommendations:

References

https://github.com/Azure/autorest

https://azure.microsoft.com/en-gb/resources/videos/inside-autorest-with-david-justice/

https://www.nuget.org/packages/autorest/

https://dzimchuk.net/generating-clients-for-your-apis-with-autorest/

https://github.com/Azure/autorest/blob/master/README.md#installing-autorest

Short Walks – Error: could not find dependent assembly

Error: could not find dependent assembly ‘System.Runtime, Version=4.1.1’

This error can occur when you have conflicting versions of a system (or any) assembly. The following is a .Net Framework feature that will redirect the assemblies to be the same, and thereby resolve the conflict:

      <dependentAssembly>
        <assemblyIdentity name="System.Reflection" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.1.1.0" newVersion="4.3.0" />
      </dependentAssembly>

Function Apps in Azure

With Update 15.3.1 for Visual Studio came the ability to create Function Apps in VS. Functions were previously restricted to writing code in the browser directly on Azure*.

Set-up

The first step is to download and install, or use the Visual Studio Installer to update to the latest version of VS (at the time of writing, this was 15.3.3 – but, as stated above, it’s 15.3.1 has the Function App update).

Once this is done, you need to launch the Visual Studio Installer again

Select the Azure Workload (if you haven’t already):

The Microsoft article, referenced at the bottom of this post, answers the issue of what happens if this doesn’t work on it’s own; it says:

If for some reason the tools don’t get automatically updated from the gallery…

I’ve now done this twice on two separate machines and, on both occasions, the tools have not automatically been updated from the gallery (it also sounds like the author of the article doesn’t really know why this is the case). Assuming that the reader of this article will suffer the same fate, they should update the Azure gallery extension (if you don’t have to do that then please leave a comment – I’m interested to know if it ever works):

Close everything (including the installer) and this appears:

Finally, we see the new app type:

Function Apps

Once you create a new function app, you get an empty project:

To add a new function, you can right click on the solution (as you would for a new class file) and select new function:

New Function

You then, helpfully, get asked what kind of function you would like:

Function Type

Let’s select Generic WebHook:

Generic Web Hook

We now have some template code, so let’s try and run it:

Running it gives this neat little screen that wouldn’t have looked out of place on my BBS in 1995**:

The bottom line gives an address, so we can just type that into a browser:

As you can see, we do get a “WebHook Triggered” message… but things kind of go downhill from there!

There are a couple of reasons for this; the WebHook only deals with a post and, as per the default code, it needs some JSON for the body; let’s use Postman to create a new request:

This looks much better, and the console tells us that we’re firing:

Publish the App

Okay – so the function works locally, which is impressive (debugging on Azure wasn’t the easiest of things). Now we want to push it to the cloud.

This goes away for a while, compiles the app and then deploys it for us:

Your function app should now be in Azure:

Now you’ll need to find it’s URL. As already detailed in this article, you get the function URL from here:

If we switch Postman over to the cloud, we get the same result***:

Footnotes

* Actually, this is probably untrue. It was probably possible to write them in VS and publish them. There were a few add-ons knocking about in the VS gallery that claimed to allow just that.

** It was called The Twilight Zone BBS; although, if I’m being honest, although the ANSI art on it was impressive, it wasn’t my art work.

*** Locally, it wasn’t that fussed about the body format (it could be text), but once it was in the cloud, it insisted on JSON.

References

https://blogs.msdn.microsoft.com/webdev/2017/05/10/azure-function-tools-for-visual-studio-2017/

http://pmichaels.net/2017/07/16/azure-functions/

Short Walks – Whatever happened to WinGrep?

Unix users will know the joy of being able to use grep to simply find text somewhere in a file in a directory, or its sub-directories. In Windows, we used to have a tool called WinGrep; however, I tried to navigate there today, and it had been taken down.

There were problems with WinGrep – it was slow, and cumbersome; but it did do what it said on the tin. Now that it’s gone, what’s to replace it?

Fortunately, when I had a look around, I found a nice little tool in powershell called findstr. You can use it like so:

 findstr /spinm /c:"mystring"

To find out what /spinm does, type:

findstr /?

FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]
[/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]
strings [[drive:][path]filename[ …]]

/B Matches pattern if at the beginning of a line.
/E Matches pattern if at the end of a line.
/L Uses search strings literally.
/R Uses search strings as regular expressions.
/S Searches for matching files in the current directory and all
subdirectories.
/I Specifies that the search is not to be case-sensitive.
/X Prints lines that match exactly.
/V Prints only lines that do not contain a match.
/N Prints the line number before each line that matches.
/M Prints only the filename if a file contains a match.
/O Prints character offset before each matching line.
/P Skip files with non-printable characters.
/OFF[LINE] Do not skip files with offline attribute set.
/A:attr Specifies color attribute with two hex digits. See “color /?”
/F:file Reads file list from the specified file(/ stands for console).
/C:string Uses specified string as a literal search string.
/G:file Gets search strings from the specified file(/ stands for console).
/D:dir Search a semicolon delimited list of directories
strings Text to be searched for.
[drive:][path]filename
Specifies a file or files to search.

Use spaces to separate multiple search strings unless the argument is prefixed
with /C. For example, ‘FINDSTR “hello there” x.y’ searches for “hello” or
“there” in file x.y. ‘FINDSTR /C:”hello there” x.y’ searches for
“hello there” in file x.y.

Regular expression quick reference:
. Wildcard: any character
* Repeat: zero or more occurrences of previous character or class
^ Line position: beginning of line
$ Line position: end of line
[class] Character class: any one character in set
[^class] Inverse class: any one character not in set
[x-y] Range: any characters within the specified range
\x Escape: literal use of metacharacter x
\ Word position: end of word

Or follow the link at the bottom.

References

https://technet.microsoft.com/en-us/library/cc732459(v=ws.11).aspx

Upgrade to C# 7.1

Async Main (C# 7.1)

Another new feature in C# 7.1 is the ability to make a console app deal with Async. Have you ever written a test console app to call an async function; for example, what will this do?

static void Main(string[] args)
{
    MyAsyncFunc();
 
    Console.WriteLine("done");
    
}
 
static async Task MyAsyncFunc()
{
    await Task.Delay(1000);
}

I’m pretty sure that I’ve been asked a question similar to this during an interview, and probably asked the question myself when interviewing others. The way around it in a console app previously was:


static void Main(string[] args)
{
    MyAsyncFunc().GetAwaiter().GetResult();
 
    Console.WriteLine("done");
    
}

However, in C# 7.1, you can do this:


static async Task Main(string[] args)
{
    await MyAsyncFunc();
 
    Console.WriteLine("done");
    
}

Upgrading the Project

Unlike other new features of 7.1, this feature doesn’t afford you the ability to “Control Dot” it. If you try to do this in C# 6, for example, it just won’t compile:

To upgrade, go to the Advanced tab in the Build menu (of project properties):

References

https://github.com/dotnet/roslyn/issues/1695

Default Literals in C# 7.1

One of the new features added to the latest* version of C# is that of a “default” literal. What this means is that you can now use the default keyword as though it were a variable. For example, if you were to want to create a new integer and assign it to its default value; you would write something like this:

int i = default(int);

But, surely C# knows you want a default int? In fact, it does, because if you type:


int i = default(long);

Then it won’t compile. Think of how much you could accomplish if you didn’t have to type those extra five characters! That’s where the default literal comes in:

Default Literal

Default Literal

You can also use the literal in comparison statements:

static void Main(string[] args)
{
    int i = default;
 
    Console.WriteLine(i);
 
    for (i = 0; i <= 3; i++)
    {
        if (i == default)
        {
            Console.WriteLine("i is default");
        }
        else
        {
            Console.WriteLine("i NOT default");
        }
    }
}
Output

Output

IL

What’s happening behind the scenes? The following code:

static void Main(string[] args)
{
    int i = default(int);
 
    Console.WriteLine(i);
    Console.ReadLine();
}

Produces the IL:


.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       17 (0x11)
  .maxstack  1
  .locals init ([0] int32 i)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  IL_0003:  ldloc.0
  IL_0004:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_0009:  nop
  IL_000a:  call       string [mscorlib]System.Console::ReadLine()
  IL_000f:  pop
  IL_0010:  ret
} // end of method Program::Main

And the code using the new default literal:

static void Main(string[] args)
{
    int i = default;

    Console.WriteLine(i);
    Console.ReadLine();
}

The IL looks vary familiar:


.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       17 (0x11)
  .maxstack  1
  .locals init ([0] int32 i)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  IL_0003:  ldloc.0
  IL_0004:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_0009:  nop
  IL_000a:  call       string [mscorlib]System.Console::ReadLine()
  IL_000f:  pop
  IL_0010:  ret
} // end of method Program::Main

Footnotes

* C# 7.1 – Latest at the time of writing

References

https://github.com/dotnet/csharplang/blob/master/proposals/target-typed-default.md

Irreducible Complexity in Agile

What is irreducible complexity?

A common critique levelled at the agile philosophy is that of irreducible complexity. The argument is very much like the argument of the same name often levelled at evolutionists. The argument typically given against evolution is this:

If evolution predicts gradual changes, then what use is half an eye?

This article isn’t about evolution, and I’ll leave the rebuttal of that to people like Richard Dawkins (if you’re interested then read the Blind Watchmaker – it’s that book that made me start writing this post). The following is a paraphrase of a concern that I’ve heard a few times:

Using the principle of gradual improvement, what if I ask for a table? I can split the story up into four separate “leg stories” and a “table top story”, but I can’t release a table with two legs.

Oddly, the concern often uses the same metaphor; so maybe there’s an article out there that I’ve missed!

A table with two legs

Certainly the above statement is true (as far as it goes), but let’s forget about tables (as we can’t create one using software – or at least not without a 3D printer). What about the following requirement:

As a sales order entry clerk
I want a new sales order entry client
So that my efficiency can be improved

Clearly we can’t have “half of a sales order entry system” any more than we can have half a table.

The first thing here is that we need some answers. Forget about the system that’s been asked for, for a minute, and consider why it is being asked. *

So that my efficiency can be improved

What are they using now, and why is it not efficient? Since there is no-one to answer this hypothetical question, I will do so myself (after going to speak with the imaginary clerk):

The sales order clerk is currently using an existing piece of software, written sometime in the eighties. It’s character based (1. Place sales order, 2. Find sales order, etc..).

I’ve just watched him (his name is Brian) create a hypothetical sales order. It took around 5 minutes, and most of the time was taken up looking up product codes using a sheet of A4 that has them printed on.

Do we really need the table

The first thing to ask here is what exactly is the minimum viable product (MVP). That is: what does the client actually need. Do they really need a new sales order system, or do they just need a quick look-up for the product?

Let me just clarify what I’m saying here: I am not saying that when a client comes and asks for a table that they are told they can have a stool with a plank of wood lashed to it, and they can like it or lump it. We are at a point now (and have been for some time) in IT where we can build anything, but it takes time; and, at this moment (2017) development time is likely more expensive than any other single part of the IT infrastructure. Furthermore, it should always be kept in mind that, during the software development process, requirements change.

But we really need the table

Whether it’s an internal or external client, they are well within their rights to ask for a complete product, and that can be quoted for and produced. The process under waterfall would be that a Business Requirement document would be produced, followed by a functional specification, which details how the stated business requirement would be solved, and finally, the software would be written to address the functional specification.

There’s a lot of room for misinterpretation here. The person writing the code can not only be a different person to the one talking to the customer, but can be three or four layers removed. Even if you ask the client to sign off documents at every stage of the process, you have to assume that they have read and understood what you have placed in front of them. There are essentially three things that can go wrong here:
1. The requirements are misunderstood, or wrongly stated, the stated functional specification doesn’t fulfil the business requirement, the code doesn’t correctly represent the functional specification, or one or more of these documents is misleading; in summary, the people producing the software get it wrong somewhere.
2. The client changes their requirement due to budget constraints, or due to changing business requirements, or external factors, or because they realise that they don’t need what has been requested anymore, or need something different, or extra; in summary: the client has changed the scope.
3. The required software is more, or less complex than initially anticipated, a new software development tool is introduced; in summary, the quoted price for the job becomes invalid.

These are not mutually exclusive: all three can happen at the same time. (The same is true for the table: the blueprints can be wrong, the carpenter can fail to follow them correctly, and the person asking for the table can realise that they need a bigger or smaller one).

What does this mean for the sales order system? What if we identified that, rather that replace the sales order system entirely, we could start by replacing the product lookup; maybe we’d raise a few user stories that asked for a simple application or web page with a look-up facility. We would identify all the parts of the system that need replacing, but we would order them, and we would arrange to show the client at regular intervals.

Again, let’s reduce that complexity further:

– Create a simple CSV text document that contains all the product codes and descriptions.
– Create a RESTful call that accepts a string and searches the product description in the database (in our case, the CSV).
– Create a console app that calls this.

Now the clerk has more than he had before! It doesn’t look much better, but he isn’t trying to find a product on a sheet of paper anymore… so the next story might be:

– Create a webpage that allows the entry of a product description and returns a product code

The point being that, at every stage, the product is getting slightly better. We can show this to the clerk, and after a few days development, he can identify any issues. We can have something that provides tangible benefit in days.

This takes more time, though!

Yes – yes it does. If you compare it to the waterfall process on paper, I think it probably does take more time, especially if you start getting embroiled in all the scrum ceremonies. But let’s consider what that means:

1. The business requirement document is right, first time.
2. The functional specification is right, first time.
3. The software is right, first time.

Because the three points above will never** be true, they get iterated. I actually read an interesting article some time ago that argued that, for this reason, waterfall doesn’t even exist as a system. Unfortunately, I couldn’t find a link to it.

So, whilst on paper it might seem time hungry, what about the following scenario: you complete the product look-up page, and the client gets a big order; they need to get a web-site to enable customers to place orders directly themselves. The requirements have changed. Thinking a few months down the line, should the web-site work, the old sales order system may no longer be required at all. In the old way of a detailed spec, sign-off and months of development, they would effectively have to cancel the order and lose the time spent thus far. Most clients these days will appreciate that, by seeing the software in an iterative development cycle, they have opportunities to change the scope that they didn’t previously have.

It’s worth remembering what the agile manifesto actually says – because it’s not a big long document. It basically says that you should talk to people – your colleagues, your clients and their customers – whoever you can: show the software as often as you possibly can; talk to the client and check that they still have the same requirements; release as often as possible and check it’s really improving things.

Agile doesn’t always work, though

There are some times when this approach absolutely doesn’t work. For example, when NASA build a new spaceship; it’s unlikely that the people that program the guidance system will be using an iterative approach to development; whilst a guidance system that sends the ship in broadly the right direction may (or may not) be better than none at all, $100B worth of kit needs a complete product. It also has a long shelf life.

However, if you consider the principle of agile, rather than the specific implementations, such as scrum, you can take some of the advice (even into NASA***).

Summary

In summary, and to blatantly plagiarise Richard Dawkins, half an eye is useful, and so is half a sales order system, and so is half a table; the key thing is to ensure that it’s the correct half, and it fulfils some of the requirements.

Footnotes

*I realise that this requirement for such a large and complex system would not be sufficient, but it serves to illustrate a point.

**Okay, I can’t prove this, but I’ve never worked on a project where these have all been right first time. It is, of course, theoretically possible.

***I don’t, and never have, worked for NASA, so I actually have no idea what the processes are. I know nothing, whatsoever, about space travel, either – this is entirely based on guesswork and conjecture. For all I know, they launch the thing, and there’s a guy sat in Houston with a joystick, controlling it.

References

http://agilemanifesto.org/

http://www.scrumguides.org/docs/scrumguide/v2016/2016-Scrum-Guide-US.pdf

http://www.first55tech.com/agile-requirements-blog/irreducible-complexity