Multiple Projects with .Net Core and Visual Studio Code

The challenge is to create a solution in VS Code with multiple projects. There are three projects

  1. A console application
  2. A web api application
  3. A library with data access code that is common to both.

It will look like this when we are finished

Expanded to show detail

We need a solution that can build out all these projects in one click. Since we using VS Code and enjoying it’s lightweightness we’ll be relying completely on the new .Net Core Command Line Interface. I enjoy a challenge so using the command line seems fun (to me). Let’s go.

(TL;DR;)

In case you don’t want to read the detail – the commands used to set up all projects, solutions and references are

From project root

Preliminary

To do this you’ll need VS Code’s C# extension installed into visual studio. Go to extensions and search for C#.

Install and away you go.

Note on command line

All .Net Core CLI commands can be entered into the terminal window in VS Code or into the standard command prompt if you prefer. Navigate to the root folder and enter your first command

Create Console Application

This installs our console application project. Since we are on .Net Core 2.0 we get the csproj file rather than the json project file of earlier versions. This installs the console app in a new folder with the same name as it’s containing folder. If we want a different name to the folder we do that by

But we don’t want that. We are keeping it simple. What I like about .Net Core is that it’s had all the gubbins stripped out. So our proj file for the console app is simply …

Nice. I understand that.

Create Common Library

Next we want to create a C# dll to host some common code like data access.

Creates an empty project called Demo.Common with a nice simple proj file thus

Link Common Library to Console app

Change to the console app direct and run the add reference common

Inserts the following into the console proj file

So the console app can access code in the common project and the two will build out together.

Add Nuget package to Common Library

We commonly want to add some nuget packages to our projects. So lets add the HtmlAgility pack and a C# driver for MongoDB – no reason for them other than I often use them.

Change directories back to common library

Now add the packages

Look at the proj file and you can see the package references inserted

VS Code likes to tell me to restore the project I.e. run dotnet restore. You don’t need to. Dotnet build or dotnet run does it for you.

Build Console Application

Let’s check things are working as they should and build our console app.

Output

  Demo.Common -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.Common\bin\Debug\netstandard2.0\Demo.Common.dll

Demo.ConsoleApp -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.ConsoleApp\bin\Debug\netcoreapp2.0\Demo.ConsoleApp.dll

Build succeeded.

0 Warning(s)

0 Error(s)

Good – by building the project we get both common and the console application building.

Create API 

Return to root folder

Now add a web api project called Demo.Api

Change to the Api folder

Now add a reference to our common library

The Api proj file looks a bit more complex but I’ll still pretty minimal compared to Visual Studio proj files.

Now let’s build that project. Staying in the Api folder

And the output shows us two projects have been built.

  Demo.Common -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.Common\bin\Debug\netstandard2.0\Demo.Common.dll

Demo.Api -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.Api\bin\Debug\netcoreapp2.0\Demo.Api.dll

Build succeeded.

0 Warning(s)

0 Error(s)

Joining everything together

Ok , so we want all the projects to build in one click. Because we have two independent applications (an API and a console app) we aren’t going to be able to do the build by navigating to a folder and building the proj file. We need a solution file to bind them all together

(this shamefully baffled me for a while. I was trying all sorts with launch.json etc… The solution is obvious though – embarrassed for not getting it immediately)

Back to root

Now add the solution file. We don’t want it in it’s own directory so omit the -o parameter. Add in the -n otherwise it takes it’s name from the containing folder which we don’t want in this case.

Now include the API and Console app

The solution file now includes the project info

Staying in the solution directory run build

And now all three projects are built.

Demo.Common -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.Common\bin\Debug\netstandard2.0\Demo.Common.dll

Demo.ConsoleApp -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.ConsoleApp\bin\Debug\netcoreapp2.0\Demo.ConsoleApp.dll

Demo.Api -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.Api\bin\Debug\netcoreapp2.0\Demo.Api.dll

Build succeeded.

0 Warning(s)

0 Error(s)

Finished!!!

Demo code

The rather uninspiring skeleton demo app is at
https://github.com/timbrownls20/Demo/tree/master/ASP.NET%20Core/MultipleProjects

More interesting the same pattern is on a .Net Core API for some Buddhist texts I’ve been working on
https://github.com/timbrownls20/Pali-Canon/tree/master/Api

So

https://github.com/timbrownls20/Pali-Canon/tree/master/Api/PaliCanon.Loader
Is the console app that parses HTML and populates a document database with the texts

https://github.com/timbrownls20/Pali-Canon/tree/master/Api/PaliCanon.Api
Is the web api to access the texts

https://github.com/timbrownls20/Pali-Canon/tree/master/Api/PaliCanon.Common
Is the model and repositories common to both.  It’s the same pattern as the simplified demo app and I’m using VS Code for that – just to try it out really.

Useful Links

https://docs.microsoft.com/en-us/dotnet/core/tools/?tabs=netcore2x
Full documentation for .Net Core Command Line Interface

https://code.visualstudio.com/download
Visual Studio Code is freely available here.

Resharper Build and Run

Just a quick shout out for Resharper’s new build and run feature. I’ve become accustomed to Resharper slowing my machine up as it endlessly loads a variety of caches and processes. Speaking as a member of the slower development machine community it is a delight to see a new feature that actually speed things up and increases productivity even on less than optimal machines. Build and run uses some heuristics (i.e. clever workings out) to analyse which projects actually need to be built then only builds these. On first build you don’t notice much of a difference but on subsequent build it makes for dramatic increases of speed. It’s impressive and a real benefit.

I won’t bore too much with my current slow machined troubles but I currently a home based contractor working on a mid range laptop – I anticipated this laptop to be used for some lightweight home development projects. Inside it’s running 2 Visual Studio instances with 35 and 12 projects each respectively. Really it can’t cope – except it suddenly can using Build and Run. 5 minutes build times have become 10 second affairs. It’s not too much to say that it has been a bit of a life (job) saver.

Of course the real solution is to buy a better machine. But as I find myself in a new, more expensive country funds are a little short right now. So until I spring for a new laptop, Resharper Build and Run is keeping me afloat. Thanks guys.

EDIT

I’ve actually now done the decent thing and upgraded my laptop to use a 500GB SSD disc and popped in some extra RAM while I was at it. It runs like a dream. I close down and reopen Visual Studio now just for the fun of it – takes seconds. I still like Resharper Build and Run though, but it’s now less critical to my health and well being.

Getting the Root Directory Path for .Net Core Applications

Quick one. Given any .Net app I want to know the root path of the application i.e. the top level directory. I was doing this with .Net Core but it puts in extra directories by default in the exe path i.e.

bin\Debug\netcoreapp2.0\my.dll

so my normal kuldgy methods weren’t working. This all works for any .Net app not just Core in fairness – it’s just that the extra stuffed in by .Net Core threw me a little. There are all kinds of ways to find this for particular applications web, windows etc.. but this should work generally. Well it worked with my little console app anyway.

The Code

Use reflection to targeting the executable and get the path

this will get you

file:///c:/development/MyApp/bin/Debug/netcoreapp2.0/myApp.dll

which is the UNC path. Combine with Path.GetDirectoryName i.e.

this gets

file:\c:\development\MyApp\bin\Debug\netcoreapp2.0

which is a  file path now and it has got us the directory of the executable. It’s still not where we want to be so use some regex

This will chop up the path and gives you

c:\development\MyApp

which is correct.

The Function

So overall a useful function for this could be

Which does what we need or I quite like it as a (much abused) extension method

Which can be called like

Which gives

c:\development\MyApp\TargetFile.cs

Job done.

The Regex

Not everyone likes Regex*. But for the aficionados here is what it is doing

For example matching this

file:\c:\development\MyApp\bin\Debug\netcoreapp2.0

Is my match – this will match a drive and a path up to

It’s a lookahead (zero length assertion). It will check for “bin” but not include it in the match

It’s a negative lookbehind (zero length assertion again). It will make sure that the letters fil don’t immediately proceed the match. This is to stop e:// being the match i.e. the e from file.

Clearly this assumes that the bin folder is directly under the root path as it normal is. If it isn’t in your app then break out your favourite Regex editor and write your own. It will make a man/woman/scared child of you.

(* Hardly anyone likes it – well I haven’t met many)

Useful Links

https://stackoverflow.com/questions/837488/how-can-i-get-the-applications-path-in-a-net-console-application
Full disclosure – the first bit of this is from this SO question. The extension I did with my very own coding fingers

http://regexstorm.net/tester
Regex storm – C# regex tester. Very good. JavaScript based testers don’t work with this as they can’t do negative lookbehinds.

https://www.regular-expressions.info/lookaround.html
Look ahead, behind and all around with zero length assertions

From Classic ASP to React

Where it all began

I’ve been a software developer for over 16 years. It’s not that long but in terms of software development it’s pretty long time. Perhaps it’s like dog years – 1 development year equals 7 normal person years so actually I’ve been a developer for 112 software dev years. That seems more like it.

Over that time I’ve seen 4 major shifts in web development. Shifts up to new versions happen all the time – this is more where everything you know needs to be put in the bin and you start up again. Seems harsh but that’s the business and if you don’t like it then it’s perhaps time to move on. I’m shifting again to Node.js and React but as I do it’s kind of interesting to look back at the other shifts and how I felt about them at the time and how good they were in retrospect.

Classic ASP

It’s where it all began. Asp files with VBScript and <% %> to poke holes in the html to fit the programming stuff in

It’s all about the response.write. I loved it.

Features

  1. Interpreted language – no compilation
  2. Written in scripting language like VBScript or JScript
  3. One file called *.asp. Everything is in there.
  4. One file per page
  5. Lots of use of Response and Request objects. Felt like you were working with the architecture of the web rather than against it
  6. Stateless

How excited was I to use it?

Ecstatically excited. I loved coding in it. Dynamic web pages that could squirt out content for each individual user. Amazing. It was all interpreted – no compilation here – no need for it. I did this for a Masters project and we all loved it. My supervisor was talking about PhDs in it.

Downsides

It wasn’t perfect. The downsides were

  1. Terrible IDE. It was MS InterDev and it was unusable. We all used to code in EditPad Pro which at least had colours.
  2. No structure. You could put COM+ components in to force some structure into it but you would only do this if you really hated your coworkers.
  3. No debugging unless you count writing acres of Response.Writes all over your code
  4. No state management at all. You want to persist the state of a textbox then do it yourself …

which sets the stage for

ASP.Net Web Forms

A proper compiled language with a new framework and new languages to boot .To get a flavour here is the ubiquitous page load event

Felt radical at the time.

Features

  1. A compiled language – Wow!
  2. Code behind – split files with markup and code in separate files combined with partial statements
  3. Highly abstracted – managed through page life cycle events
  4. Stateful – Automatic state management through View State

How excited was I to use it?

Passed myself with excitement. I got to build a new server first to host it and I had a big silver machine on my desk making a sound like an aircraft for months. And that was just the start – new language, new IDE that worked, proper code and architecture. Who wouldn’t like all this.

Downsides

The world moved past webforms and while they were good initially, the advent of more client side techniques such as AJAX showed it’s limitations

  1. Worked very badly with JavaScript. WebForms mangled HTML element ids and made it difficult to work with
  2. It was really like windows programming for the web. While hiding the complexity of the web might seem good I’m convinced that webform programming led to a cohort of web developers who really didn’t understand the nature of the web.
  3. Inefficient – lots of postbacks and ViewState (stashing the state of the form to persist it) was massive and came over the wire every time.
  4. Very difficult to unit test. Too many tightly bound dependencies
  5. In the end I hated some of the components. Some were good like ListView and some were made for abuse and torture such as the UpdatePanel. Nest these babies and watch the bad times roll.

Things looked a lot brighter over at the Rails community so we got …..

ASP.Net MVC

Model, View Controllers in the Net world. It was a proper architectural pattern that was fully unit testable. It wasn’t pretending to be windows programming – it was the web and it was proud of it. Clearly still very much used today.

How excited was I to use it?

It wasn’t so much as excited – I was relieved. After fighting against webforms, here was something that worked with you. It was almost back to classic ASP in some ways so I felt like I was coming home.

Features

  1. Skinny controllers, dumb Views and fat models
  2. Clever routing so it wasn’t one file per page any more. That more than anything amazed me
  3. Worked well with dependency injection so was testable
  4. Worked well with JavaScript. Generally felt like the web
  5. Stateless again

Downsides

Honestly I just like MVC and always have done. If pushed I might say

  1. It still posts back so not as responsive as it could be
  2. It’s a different stack to front end so you would need to know C# and JavaScript
  3. It’s easy to write badly – massive Views full of logic aren’t good

But while we weren’t looking Node.js was discovered and we get….

React

Or I could have said Angular or Ember or fill in the blank with your favourite framework. For me, it’s the most radical shift yet because it’s not the Microsoft stack – we’re not in Kansas any more. It’s all in JavaScript, even the server. And while it’s not restricted to the client it’s focus is around ‘reactive’ single page applications (well my focus is anyway).

Features

  1. Highly componentised
  2. JavaScript with HTML like syntax embedded in
  3. Single page application (often)
  4. View only .
  5. Blazing fast if on single page app – uses Virtual DOM to only update what it needs to on the page
  6. Back to stateful (if on single page app)

How excited am I to use it?

I feel pretty fortunate to have to opportunity to use this in a commercial setting. I’ve always liked JavaScript and it’s fascinating to see it build out a large scale application. I like Angular for the same reason. So I’m excited once again.

Downsides

It’s not all gravy though. Downsides include

  1. It is a steep learning curve and fast moving so the curve keeps shifting
  2. It’s JavaScript which is great but it’s easy to write terrible JavaScript so terrible React
  3. You’ll need a decent architecture to go with it like Redux – not a disadvantage but you need to be aware of it
  4. It’s just the view so the rest is up to you to (re)invent.

Looking Back and Looking forward

I feel all misty eyed looking back and this is just one aspect of the development I’ve been involved in. There’s ORMs, mobile development, testability, ASP Core, the rise of Dev Ops and on and on and on. Headspinning but great.

What’s next – it’s just so hard to say. I reckon .Net Core will take off, JavaScript will be replaced or transform to something unrecognisable, everyone will decide they hate ORMs and rediscover stored procedures, machine learning will be big, driverless cars will start to fly and we will all go to live on Mars with Elon Musk. Or maybe someone will invent a web framework which combines the best of classic, web forms, mvc and react; perhaps like this ……

  • The simplicity of classic ASP
  • The rapid development capabilities of web forms
  • The testability of MVC
  • The blazing speed of React

Can someone invent that one please.

Useful Links

https://www.w3schools.com/ASp/asp_examples.asp
Classic ASP examples

https://msdn.microsoft.com/en-us/library/ms178472.aspx
WebForms page management life cycle

https://www.asp.net/mvc
Microsoft site for MVC

https://reactjs.org/
Main page for react from FaceBook this time

Shorter syntax for Node.js module import

I’ve found myself writing a lot of import module statements during React development that I could have shortened. It’s a bit dispiriting when everything above the fold in your code is a boilerplate import. To give an example – this very simple React page

(this demo app is so bland I actually tarted up the image in photoshop – and it’s still bland)

Is constructed from this component

Even in this simple example, I’ve a bunch of imports from the same Alerts module. This could potentially go on and on and has done when I’m using something like React-Bootstrap. It’s not pretty. Happily this can all be shortened to one line thus

When I first saw this I found it baffling and unexplained – especially when just importing 1 object from a module e.g.

Suddenly there is curly brackets in the way. What’s all that about?

It’s all in the Destructure

It’s using ES6 object destructuring to do this magic. A simple example of object destructuring would be

The first object is automatically split into 2 variable when assigned – this is the destructuring

So our react import is the same as this in essence. Label.jsx is the component (object) we are importing

The export at the end is what is going to be destructured – we could simplify this further and omit the property names (with more ES6)

Anyway that’s not strictly relevant. Explaining onwards – the require squirts out the object and the destructuring assigns it to 3 variables which we can use in our page

This can be rewritten as an ES6 import statement which will transpile down into require with something like Babel if need be.

It’s this form in particular I often see in code samples and the like. So that’s explained then and a little bit of the grey fog has lifted. Lovely.

Useful Links

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
ES6 Destructuring – good detailed explanation

https://blog.risingstack.com/node-js-at-scale-module-system-commonjs-require/
This is all underpinned by Node.js CommonJS module load pattern – that’s the require bit. More detail above.

https://github.com/timbrownls20/Demo/tree/master/React/CommonJSDemo
The sample code isn’t much but as ever the code is on my GitHub site. It’s using webpack as the task runner which is different to the gulp runner I’ve been using. Probably better if I’m honest.

 

 

Only 92% Happy According to Cognitive Services

I’m particularly pleased with the photo of myself on this blog. I normally look a bit odd on photos but this one was taken about 2 days into a new job for an id card. I still had the new job glow. I was relaxed, tousled haired and the future lay ahead bright and clear. I look happy. So I thought I would upload it into Microsoft Cognitive Services Emotion API to get the confirmation that was indeed 100% happy.

I am shocked that even at my most happy I only achieve 92.8% happiness. My British reserve clearly means that I hold back 7% for that neutral stiff upper lip feeling. There are flickers of other emotions with contempt peeking out. Where does that come from ? It’s a new job. Surely contempt should only be registering when I’ve been there a month or two. I uploaded an uncropped image of myself a few months previously and I was registering about 3% fear . The only difference is that the very top of my head was visible that time. I’ve clearly got a very fearful haircut.

Is there a serious point to this? Probably not but it is my first foray into machine learning and as a professional software developer it certainly won’t be the last. I’m pretty fascinated about it. I hope I can start to register 100% happiness when I get into it more. At least 95% – come on!

Another Free JavaScript Book

My least viewed blog post is the one about a free JavaScript book. So building on that lack of success here is another post about another free JavaScript book. You don’t know JS: Up and Going by Kyle Simpson is currently retailing for zero pounds and zero pence (or zero dollars if you prefer) at Amazon kindle store and it is worth a read.

It’s a brief trailer for the other 5 pay for books in the series but does a good job of going over the basics and the not so basics. Mr Kyle makes the interesting, and probably correct, argument that it’s possible to write entire applications in JavaScript without knowing a lot of the language. It certainly accords with my own experience – there is a lot of dodgy JavaScript around and not so much well crafted stuff. So he’s issued a bit of a call to arms for developers to learn all the language and not just the ‘Good Parts’.

I’m not sure if I’m going to read all the books in the series but I’ve bought the ES6 one and that’s also very good but sadly not free. I guess the man’s got to be paid somehow.

Accessing form data with React.js

Accessing form data seems a standard thing to be doing so I disappointed myself and my entire family when I couldn’t do it straight away with when using React. After a little thought and a bit of practice I implemented 3 ways of doing it thus redeeming myself in the eyes of my relatives and co-workers. For additional redemption I’ve written up the 3 ways with an extra one tagged on the bottom.

The Demo Application

The demo application is a Todo list implementation. We can add and delete our todo tasks from the list. We can even change their colour (though that’s not hugely relevant for this but I’m bizarrely quite pleased with it).

The react component hierarchy is a bit more complex than my last demo app but nothing to get too alarmed about


  • Application
    • Header
    • TodoList
      • TodoItem
    • TodoInsert

The application state is held at the application level and all changes are handled there. I don’t want the application state spread out willy nilly throughout the components.

The Task

When I add a task then I want my application to access the name I type in the select box. The state is handled at the application level so the form data (todo task name) needs to propagate up to here. Easy – well let’s see.

Solution 1: Using ref to access the text box

The principle here is the use of the ref attribute to expose the textbox DOM node to React. Once this is done I can grab the value and pass it on.

Full code

TodoInsert component

The majority of the task insert magic is done by the TodoInsert component shown below.

Application Layer

The application layer receives the textbox value and passes it into the application state.

Code explanation 

The key thing is the use of refs within the TodoInsert component

This makes the input box DOM available within the component i.e

which we can access on the click handler

And grab the value and pass onto the addTask method we have passed in from the application layer i.e.

So the value passes to addTask method on the application layer which we can then use within the application to set and update the state. So the textbox value becomes available to the application layer. Job done ….

Evaluation

Well kind of job done. I’ve read people really objecting to the use of ref and tying the application tightly to the DOM. With those objections in mind here is an alternatively implementation without refs.

Solution 2: Using onChange to track the state of the text box

This time we are going to fire an OnChange event whenever the text changes in the text box. The general flow is

  1. Text is typed into the text box. When the text is typed in onChange event fires.
  2. The onChange event updates the state of the component. The component has it’s own state in addition to the state of the main application component
  3. When the form is submitted the form triggers an onSubmit method.
  4. The onSubmit method picks out the value from the state and passes it onto the Application layer.

Full Code

Todo Insert component

Note we are now using an entire form in this component and it now has it’s own state

Application layer

The application layer is unchanged from the first example but I’ll reproduce for completeness

Code explanation 

Let’s work through the application flow again and link it to the relevant pieces of code.

  1. When the text is typed into the text box an onChange event fires.

  1. The onChange event updates the state of the component.

  1. When the form is submitted the form triggers an onSubmit method.

  1. The onSubmit method picks out the value from the state and passes it onto the Application layer.

Remember the props.addTask method is passed in from the Application layer – so this is the link back up the stack into the main Application section.

Evaluation

This works perfectly well with no ref usage. It does cause the TodoInsert render method to fire frequently. This is only going to update the text node of the textbox so doesn’t cause any notable performance issues. We’ll reused code from the previous 2 examples for our final work through.

Solution 3: Accessing the state of the text box from the parent control

The final method is to change focus and access the component state from the parent application. It can be done and it will be done.

Full Code

Todo Insert component

This time we have omitted the form tags again and the button just handles the clicks.

Application Layer

This time the application layer has changed slightly as well. The application layer is now responsible for accessing the state in the child component.

Code explanation

Working through the flow of the application ….

Text is typed into the input box and the onChange event is fired

The click event handler now tracks value within the components own state as in the previous example.

When the add button is pressed then a click handler is fired

This then triggers a method on the application component. We don’t pass up the state this time – we are just notifying the application layer that it is time to save.

Back to the application layer we are now putting a ref instruction into our entire TodoInsert component

Which then allows us to reference the state within the todoInsert component when we are adding the Todo task

The important part being this

i.e. we are accessing the state of the TodoComponent itself – this is how we are passing around the form values.

Evaluation

Although the is more complex then the previous two examples I like this one. It enables us to manage the form values within the component and pick them out from higher up in the application hierarchy. I feels nicely encapsulated too me and I can see it extending nicely.

Additional thoughts

All three methods of passing form state around work so take your pick. I’ve used them all in various places. If I had to pick my favourite it would be the one that I’m not writing about at the moment – flux architecture. Putting in flux architecture would enable me to access the values anywhere via a store – a topic for another day perhaps. A foreshadowing teaser if you will.

Notes on sample code

I’ve simplified the code throughout and put it comments where omission occur. The entire source code is available on my github site and I’d encourage interested parties to look there for working code samples. Specific amendments and shortcuts are ….

  1. ES6 classes are used throughout. A little bit of syntactical sugar to simplify.
  2. There is a FullRow component that I use to simplify the markup but it is just that – the markup for a fullrow in the UI so just read it as that.
  3. I’ve removed all css classes from the markup. For our purposes they are just noise and serve to distract
  4. I have omitted a lot of the setup in the constructor. Again it’s boilerplate and a distraction but for the interested here is an example of what you are missing

Useful links

https://scotch.io/tutorials/better-javascript-with-es6-pt-ii-a-deep-dive-into-classes
ES6 classes. Used throughout the code samples.

https://stackoverflow.com/questions/35303490/uncaught-typeerror-cannot-read-property-props-of-null
I missed out the constructors in the code samples. One of the things is the boilerplate code to bind the this keyword to the scope of the function in the classes i.e.

The above link is a good post on what that’s all about plus some ES7 syntax to render this unnecessary

https://facebook.github.io/react/docs/refs-and-the-dom.html
Official guidance on the use and abuse of refs from Facebook.

https://facebook.github.io/flux/docs/overview.html
Flux architecture articles again from Facebook. Another method to pass around form data and perhaps my preferred one.

https://github.com/timbrownls20/Demo/tree/master/React/TodoList
As ever, all code is on my GitHub site.

Simple Debug Panel for React.js

A few months ago I wrote about implementing a debug panel in AngularJS. I’m just getting into React.js so I thought I would do the same by way of comparison. Maybe I’ve become a less complex person in the intervening months but I found the React implementation a lot simpler. It just kind of fell out.

The Problem

I want a panel that will display the current state of my react application that can be easily turned on and off.

The Demo Application

My demo application is a timer application. We can start, stop and reset the counter. It’s not the application that is going to kickstart my unicorn tech startup but it will serve for this purpose.

The react components of the simple timer are, well, simple.

  • Application
    • Header
    • Button (Start/Stop)
    • Button (Reset)
    • Label (Output)
    • Label (Debug Panel)

So the debug panel is just an instance of the my label component.

The Implementation

Label Component

This is a bootstrappy label that takes in a couple of properties. In it’s simplest form the render method is

So it returns some JSX that can take a prop value that sets the label text. We build it from a parent component like this…

Adding a bit more complexity we can toggle the visibility which is one of our requirements for a debug panel. So adding this in and taking the opportunity to show the entire label component

So now it has a property ‘visible’ that can show and hide the label which we call thus

The Debug Label

The debug label is just a variant on how this label is constructed. I’m holding my state at the application level – I don’t want it scattered around my lovely simple timer willy nilly. The component is the same and it is constructed from the application component like this…

with the state parsed to a string and passed in. It renders like this

So I can easily see the state of the application. It can be turned off easily with the visible prop

Though to toggle on and off does require a rebuild (with gulp in this case). I don’t think this is a significant hardship.

Further Thoughts

I am aware that I’ve basically implemented a very simple version of the chrome developer toolbar but I still like it. I like to see the state up front and it’s a simple little thing that shouldn’t cause anyone any problems or upset.

I could enhance it a bit – changing the colour of the debug panel or doing the stringify in a dedicated debug panel which consumes the standard label. But once it was done I was happy and didn’t want to tinker. It was also notably simpler than the Angular implementation but I feel react itself is a simpler proposition and living in simpler times is no bad thing.

Useful Links

As ever the source code can be found at my github site
https://github.com/timbrownls20/Demo/tree/master/React/SimpleTimer

The styles are generously provided by bootstrap. Documentation can be found here
https://getbootstrap.com/docs/4.0/getting-started/introduction/

React homepage from the Facebook mothership
https://facebook.github.io/react/

 

HTTP 301: Moved Permanently (to Australia)

After 18 months in the planning I am formally issuing a HTTP 301 request for the Brown family – we are emigrating to Australia. Right now our life has been dismantled and put in a 20 foot shipping container – I’m surrounded by removal people, boxes and general chaos as I write. We fly out in two days and land in Brisbane on 10th August where we will reassemble the Brown life in sunnier climes.

I’m very excited / tired / sad / hopeful plus a number of other emotions that I don’t know the names of. But whatever happens it will be an adventure. I do know that you regret the things you don’t do; you don’t regret getting out there and giving things a go – a fair go.

So the 301 request has been sent. As Wikipedia (almost) says

The HTTP response status code 301 Moved Permanently is used for permanent software developer and family redirection

Wish us luck!!