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.

 

 

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/