Tuesday, May 13, 2025

Enabling PNPM in AWS Amplify Gen 2

 Hi,

Having trouble enabling PNPM in your AWS Amplify Gen 2 project?

Not a problem here is the YAML configuration


Happy coding!

Wednesday, January 1, 2025

 .NET Web API / MVC Request Body

A shortie but a goodie

Ever want to look at the request body, the request headers and so on in .NET Web API ?

https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Well, that doesn't exactly tell you how to do it. In fact, nothing does. Microsoft wants you to work at a higher level of abstraction than looking at the request. But we all know that isn't always a good idea or possible. Time to quit back to NodeJS?

If you look at Stack Overflow you will see many answers like this

string result = await Request.Content.ReadAsStringAsync();

One problem. It doesn't actually work.

* It might return an empty string
* It might hang the application
* It can deadlock
* Evil happens

So don't do it

What do you do instead?

Well, not to worry there is actually a very simple answer that's so simple it should be in the Microsoft examples (but it isn't). Hundreds or thousands of hours of experience and debugging contributed to finding this answer (or one lucky StackOverflow post you choose what to believe). You could look for this answer for ten sprints and not find it.

You will now receive this answer.

public HttpResponseMessage Get(HttpRequestMessage message) { // Access the message body here!
var content = message.Content.ReadAsStringAsync();
Task.WaitAll(content);
var body = content.Result; }

With great power comes great responsibility -- take a deep dive into Tasks (and Microsoft in general) in this man's blog here https://blog.stephencleary.com/2014/04/a-tour-of-task-part-0-overview.html but for those who just need to access the request body (which in NodeJS takes two seconds) the above should work

Of course ask yourself the question if you really want to use the Request Body. If you really need it.

Happy Coding!

Sunday, March 24, 2024

Advanced React Hacks 5/10 - "Old School" Events

Another "advanced" tip coming!

Consider the following situation
  • You're required to communicate between components in different locations at the component hierarchy. Perhaps they aren't even in a parent child relationship
  • Some functions are involved, maybe some loops. This code is already done, and already works.
  • Perhaps, some refs or other outside-of-React escape hatches are involved. This code is already done, and already works
  • And of course the usual restriction of a "professional" software developer -- don't change too much, and anything you change must be regression tested and so on and so on!
You consider several solutions
  • Since functions and loops are involved, you can't use hooks (at least not inside the functions or loops)
  • The code is already done; you don't want to refactor everything and besides you're not sure that refactoring everything will lead to a better solution anyway because it's a one-off
    • Ideally all the information should have been stored in a central location and flow down to all the required components, but that bus is gone
      • Besides, the days of storing a property, modifying it with two-way data binding and binding to that property are long since over (this isn't Knockout or Backbone!)
        • Besides, even if you did it, you would have to modify enormous amounts of already completed code, possibly create regressions, and pass down props many levels!
  • Seems like a perfect situation to use Redux (Redux Toolkit) or some other state management but besides the fact you can't use hooks, you don't want to mess with the global store and it seems wrong to use it for the one-off
  • You look at some solutions like HTML5 local storage, but that's already outside of React and you would somehow have to subscribe to local storage anyway
    • Besides, the usehook-ts package doesn't properly install
      • Besides, after copying the usehooks-ts package, it's a hook, so you can't use it in the functions anyway!
What do you do now? Is React so obtuse that you really can't deal with this situation in any way?


Are you doomed to a sprint carryover and total humiliation, just because React sucks monkey balls?



There is an answer
Forget React
Forget Hooks
Forget Frameworks
Forget react.dev documentation (except for this )


JAVASCRIPT




// inside a custom hook if you want to reuse this...
// put custom hook inside component you want to rerender...
// or just put this inside the component...

useEffect(() => {
  const func = {
    // code to subscribe to...
  }
  window.addEventListener('cool-event-name-make-it-constant', func);
  return () => window.removeEventListener('cool-event-name-make-it-constant', func);
});

...

// inside the function you want to trigger an event from
// Normal JavaScript!
// setTimeout is the secret sauce when dealing with refs! (may not be required)
setTimeout(() => {
  window.dispatchEvent(new Event("cool-event-name-make-it-constant"));
}, 10);



So remember the basics, and when React fails you, just use ordinary JavaScript

The dispatchEvent() method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().

Calling dispatchEvent() is the last step to firing an event. The event should have already been created and initialized using an Event() constructor.

The best documentation

Sometimes the old ways are the best ways


Hope this helps someone!

Friday, February 9, 2024

Advanced React Hacks 4/10 - Prevent Rerenders

Advanced React Hacks 4/10 - Prevent Rerenders


Very obvious when you see the answer (and actually documented on react.dev, link later) but still worth mentioning for posterity.

You don't want to render too much, because one point of React is that it minimises the amount of rerenders on a screen (or is supposed to)


How do most working React developers see this? With the "highlight updates" tool of course


But, it is worth mentioning (in case it happens again, and for a lesson) that in 2019 with React Developer Tools v4, this killer feature was removed


To the React Team's credit, they restored "Highlight Updates" quickly

Anyway how do you prevent re-rendering? It's actually easy

Once the component has been initially rendered, you can trigger further renders by updating its state with the set function. Updating your component’s state automatically queues a render. (You can imagine these as a restaurant guest ordering tea, dessert, and all sorts of things after putting in their first order, depending on the state of their thirst or hunger.) React.Dev "Managing State"

If you see too much of your screen rendering making it slow when taking actions (like clicking) break it down



Make more components... obvious, but worth mentioning the obvious

Until next time...


Saturday, February 3, 2024

Advanced React Hacks 3/10 - Dynamic GraphQL

Advanced React Hacks 3/10 - Dynamic GraphQL

Eventually you will reach a point in your career where you need or want to make dynamic GraphQL queries


At first it will seem "advanced" especially when looking at Google or Stack Overflow answers

You probably are used to static queries strongly typed from a schema.graphql with autocomplete in VSCode

How the hell can that change or be data driven?



Well the answer is in the specification

Typically validation is performed in the context of a request immediately before execution, however a GraphQL service may execute a request without immediately validating it if that exact same request is known to have been validated before. A GraphQL service should only execute requests which at some point were known to be free of any validation errors, and have since not changed.

For example: the request may be validated during development, provided it does not later change, or a service may validate a request once and memoize the result to avoid validating the same request again in the future.

Request may be validated during development => request may be validated during runtime => request may change!

For example with graphql-tag

GraphQL strings are the right way to write queries in your code, because they can be statically analyzed using tools like eslint-plugin-graphql. However, strings are inconvenient to manipulate, if you are trying to do things like add extra fields, merge multiple queries together, or other interesting stuff.

That's where this package comes in - it lets you write your queries with ES2015 template literals and compile them into an AST with the gql tag.

With string interpolation, "dynamic GraphQL" is actually trivial! Just build the string! (And this is JavaScript not Java so you don't need a StringBuilder!)

So,

a) RTFM (in this case the specification!)

b) Never trust the "right way"

c) Look for an existing solution

d) Probably more things I haven't thought of...

Back to basics!


Hope this helps someone!

Saturday, January 27, 2024

Advanced React Hacks 2/10 - Dynamic JSX

 Advanced React Hacks 2/10 - Dynamic JSX

What if you want a data driven application that renders JSON (not HTML obviously, always BBCode!) as JSX?



One way is React.Children


Instead do this,

export const Component = ({ children }: { children: ReactNode }) => {
  const isArray = Array.isArray(children);
  return (
    <>
      {!isArray && children}
      {isArray &&
        children.map((child, index) => {
          return <div key={index}>{child}</div>; // do stuff to the child here
        })}
    </>
  );
};

Now you can use it

import { Component } from "./Component";

export default function App() {
  return (
    <div>
      <Component>test</Component>
      <Component>
        <div>test2</div>
        <div>test3</div>
      </Component>
      <Component>
        <div>test4</div>
        <div>test5</div>
      </Component>
    </div>
  );
}

(Wow pasting from CodeSandbox worked!)

https://codesandbox.io/p/sandbox/cranky-haslett-749y8y

Hope this helps someone!

Sunday, January 21, 2024

Advanced React Hacks 1/10 - Conditional Hooks

Advanced React Hacks 1/10 - Conditional Hooks

 According to react.dev "Rules of Hooks" you cannot call hooks inside a condition

https://react.dev/warnings/invalid-hook-call-warning#breaking-rules-of-hooks

But what if you want it?


Use components!

export const ParentComponent = ({ component }: ParentComponentProps) => {

  /* derive condition here */
  // const condition = false;
  const condition = true;

  /* derive property here */
  // cont property = 0;
  // ...

  return (<>
    {
      condition && <HookComponent hookProperty={property} />
    }
  </>);
}

export const HookComponent = ({ hookProperty }: ChildComponentProps) => {
  useCustomHook(hookProperty); // could be anything!
  return <></>; // yes, components can render nothing
}

With great power comes great responsibility!

Hope this helps! More next time...

Sunday, July 3, 2022

Yarn 2 and Yarn 3 Unrecognized or legacy configuration settings found

If you get this error

Unrecognized or legacy configuration settings found

while running Yarn 2 or Yarn 3 it's possibly because you have a rogue environment variable YARN_XXXX in your environment

In my case, it was a YARN_WORKSPACES environment variable I accidentally created while using the Netlify BaaS that I was supposed to create with NETLIFY_YARN_WORKSPACES

Delete the rogue environment variable (in this case from Netlify's Build GUI but in other cases could be from your Dockerfile or CI/CD pipeline) and your problem will disappear

Basically yarn is a busybody and if it sees YARN_XXXXXX in your environment, it will complain if it doesn't recognise the environment variable and fail your build

I discovered this by modifying the build command to use yarn config -v to see the list of errors and it was an undocumented yarn error code

See https://yarnpkg.com/advanced/error-codes#yn0050---deprecated_cli_settings for another Netlify configuration error

Hope this helps someone!

Sunday, December 16, 2018

Debugging Multiple Projects in Visual Studio 2017

Hi,

Been a long time so here it goes -- debugging multiple projects

If you look around a lot you will eventually find this

https://docs.microsoft.com/en-us/visualstudio/ide/how-to-set-multiple-startup-projects?view=vs-2017

But actually, you can't do that well



Crunchify.com - RESTful Introduction
(the most important picture in the world my friends Java but I liked the picture)

So here is what you do, if you want to debug dotnet core webservices

* You publish in debug mode to folder
* Startup the project after setting ASPNETCORE_ENVIRONMENT variable

(Do PowerShell for powers)

* Now startup your web project / console program / whatever is going to contact the service in Visual Studio
* Now back to OLD SCHOOL and ATTACH TO PROCESS

(I know, greatest window in the world)

So it's a little pain in the ass to get it to work especially if you debug a lot. Attach to process every single time. But the key is dotnet core comes with its own webserver (Kestrel). You don't need IIS anymore and you don't need IIS Express anymore.

I am sure there's some crazy way to get it working with IIS / Visual Studio integration, remote debugging, etc., etc., but this way works and doesn't involve downloading a half dozen things and configuring IIS (which is half the point of dotnet core, lol). It also gets you ready for the day everything is on command line and you don't need Visual Studio (yeah, right).

Happy Coding

Sunday, May 13, 2018

Ungzipping Gzip Compression Without HTTP Headers or With File Size Limit

Ungzipping in the Browser

Sometimes, developers get given tasks outside of their usual area of responsibility. For example, dealing with gzipping.

Gzip-Logo.png

Gzip is a compression algorithm that's existed for over 25 years. It's a standard on the Internet and almost everything is served gzipped if it is served properly. There's various ways to deal with this, for example just letting the webserver gzip on the fly. However, you may run into a situation where that is impossible. For example, you may have some artificial limit of file size of less than 1 MB.

https://docs.microsoft.com/en-us/azure/cdn/cdn-troubleshoot-compression

(no code splitting is not always an answer; in particular, if you have an integration between different products, code splitting creates an unstable integration between two different products with different release cycles. a little bit of knowledge is a dangerous thing without the details.)

And of course even if you managed to gzip, if the infrastructure cannot guarantee the CONTENT-TYPE and CONTENT-ENCODING HTTP Headers and even more HTTP headers like Vary: Accept-Encoding, then the browser may decide to download the gzipped files instead of ungzipping by itself. Or simply crash.

https://blog.stackpath.com/accept-encoding-vary-important

It is also a general ask for JavaScript developers, particularly on full stack JavaScript (for example with Express as the webserver) to deal with gzipping manually. However, who knows where it will be served? It could be served on Apache, on IIS or on a CDN. So chances are, you will be asked during your career to gzip files where

a) you cannot guarantee the HTTP headers

or have other restrictions such as

b) cannot guarantee the file size (as of May 2018, there are 400 issues open in the webpack issue tracker for the split by file size . Even if code splitting by file size (actually called chunking) is done, it's experimental and bug ridden. And besides, splitting into many files is not compression... unless you serve over HTTP2 serving many files introduces an overhead. Gzipping is a standard, it must be done and the gains are too big to ignore. We are looking at gains of 5 to 10 times.

https://css-tricks.com/the-difference-between-minification-and-gzipping/

(in case you are wondering, no you cannot access the browser's native ungzip facility with JavaScript -- that is only accessible if the HTTP headers are present, and you never have access to the raw script text anyway due to cross origin policy so you will be looking at an AJAX request. If you can't make an AJAX request because of missing Access-Control-Allow-Origin or missing whitelisting tough shit, you got much bigger problems).

So what is a developer to do? Wash his hands and blame the ops guys? Who cares about gzip right, it's not our problem it's the server's problem. In fact who cares about user experience at all it can take ten seconds to load we will just wash our hands of these stupid server troubles. We are not server guys we are developers who cares about HTTP headers and how it's hosted right?

Image result for troll face

Of course not. Let's put the Dev back in DevOps and ungzip on the fly, with or without HTTP headers, on any infrastructure (well except for the Access-Control-Allow-Origin header that everyone has). Yeah baby! It will be dirty, messy but it will work.

Build Process

You can gzip in many ways, for example with this plugin if you are using webpack.

https://github.com/webpack-contrib/compression-webpack-plugin

You can also just use the Linux gzip utility as part of your build process.

The Client Side Code (or, the SECRET SAUCE)

We will use the library pako.js to ungzip on the fly, with or without the correct HTTP headers.

http://nodeca.github.io/pako/

In order to make sure the JavaScript files load in the correct order, we will use JavaScript Promises (which we will require a shim for IE support) and the JavaScript Fetch API (which also requires a shim for IE support). These are the required libraries.

https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.4/fetch.min.js
https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.1/bluebird.min.js
https://cdnjs.cloudflare.com/ajax/libs/pako/1.0.6/pako.min.js

We fetch, paying attention to three things

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

1. Load scripts in the correct order
2. Deal with HTTP errors with a CheckXHR method (write this!)
3. Fallback to the JS version, should an error occur

fetch('http://www.example.com/test.js.gz')
   .then(CheckXHR)
   .then(function (response) {
      return response.arrayBuffer(); // important to pass to PAKO.JS as array not as string
   })
   .then(function (arr) {
      return injectScript(arr);
   })
   // load more scripts here
   .onError(function (response) {
      // deal with error... I suggest loading the ungzipped JS files as a fallback here
   });


We will dynamically inject the script, again returning a JavaScript promise on completion. Because we are dealing with text in the inner HTML tag, we don't have to use onload or onreadystatechange (IE).

function injectScript(arr) {
   return new Promise(function (resolve, reject) {
      var script = document.createElement('script');
      script.text = pako.ungzip(arr, { to: 'string' });
      document.head.appendChild(script);
      resolve();
   });
}



And there we go, complete.

With great power comes great responsibility; make sure you measure the performance in the browser to see the decrease not only in file size but how long it takes to actually use the web application.

Hopefully this helps someone

P.S. Message to server guys : we can code on a 386 or a RaspberryPi or a Commodore 64 or TRS-80 or string and yarn and foodstuffs and  but that doesn't mean it's a good idea or a good use of time or money or resources. Upgrade your infrastructure to allow gzipping of any arbitrary file size with the correct HTTP headers and make the infrastructure work with the developers not against them, because the next time the problem might not be so (un)easy to solve.



Friday, May 4, 2018

Microsoft Surface Can't Connect to WiFi

Hi, leaving a quick note here for people

If you cannot connect with your Microsoft Surface or Surface Pro with WiFi to any Internet and have tried everything else, look at the date

Image result for microsoft surface os change date

The WiFi will refuse to connect without a correct date... you don't have to be exact to the millisecond, but you do have to be within the minute range particularly with corporate networks

Change the date and time manually to match the correct date and WiFi may magically work again

This is after disabling IPv6 and other various suggestions you may find elsewhere -- do some Googling

Hope this helps someone

 ~ B

Sunday, January 8, 2017

Our Responsibility as Programmers

Just read an article by Robert Martin, of "Clean Code" fame (if you haven't heard of Clean Code, read it -- it's probably the seminal text for clean object-oriented programming... some of the advice in it is dated with test-driven development and Java, but it is worth a skim at least)

"Without software: Phones don't ring. Cars don't start. Planes don't fly. Bombs don't explode. Ships don't sail. Ovens don't bake. Garage doors don't open. Money doesn't change hands. Electricity doesn't get generated. And we can't find our way to the store. Nothing happens without software. And what is software? Software is a set of rules."

Also, this

"If the ranks of programmers has doubled every five years, then it stands to reason that most programmers were hired within the last five years, and so about half the programmers would be under 28. Half of those over 28 would be less than 33. Half of those over 33 would be less than 38, and so on. Less than 0.5% of programmers would be 60 or over. So most of us old programmers are still around writing code. It's just that there never were very many of us.
What does this imply for our industry?
Maybe it's not as bad as Lord of the Flies, but the fact that juniors exponentially outnumbers seniors is concerning. As long as that growth curve continues[4] there will not be enough teachers, role models, and leaders. It means that most software teams will remain relatively unguided, unsupervised, and inexperienced. It means that most software organizations will have to endlessly relearn the lessons they learned the five years before. It means that the industry as a whole will remain dominated by novices, and exist in a state of perpetual immaturity." - Robert Martin
Basically the problem is this, more in 2017 than ever -- the world has unwittingly ceded control of its financial, healthcare and private personal information for better or worse to computer programmers. We have a duty to create systems which are maintainable, robust and error free, even if it costs us in the short term.

What are the problems? The problems are in-your-face, serious, and unfortunately have nothing at all to do with coding or computer programming.

Example #1 (easy): Boss asks for deadline, you can take a shortcut. Either you can take a shortcut, or take 20% more time... piss them off now and make them happy later, or go for the short term gain.

Example #2 (hard): You are in a responsibility of great authority to pick a framework or a technology and you can either choose what is cool and hot, and therefore good for your career (great, one more line for your resume!), or choose proven but less cool and less interesting technologies. Balance this against whether or not the technology is about to go out of the market (you can write a website in COBOL but it is NOT a good idea!)

Example #3 (very hard): You have the ear of business people, and you must convince them of the need to create a process or build a framework or library which has no readily apparent business value and no readily apparent use cases, but will increase developer productivity ten-fold down the line, or allow you to enter emerging markets or attack potential competitors.

Example #4 (extreme): You must either sacrifice personal time and personal emotion and energy to create a process / library / frameworks for your company or down the road you see the end of your company or business (at least tech-wise)... the tech is so bad nobody will want to work there or stay there, you see the train coming a mile away but you are superglued to the tracks at least at work. So you either have to sacrifice, in order to move the company in the right direction, and get 0 credit for it, or hold your tongue and hope that the world works differently than you think.

What are the answer to these problems? I could give my answers, but they would be my answers.

The point is, there are no right answers... it depends on the situation, the market, and most of all experience. And, if Robert Martin's numbers are to be believed, experience is severely lacking.

I don't pretend to know anything about making money or business. Maybe markets are all about point in time and maybe writing spaghetti code and awful code is the way to do it -- forget about "tech" things like build processes, GitHub, Open Source, frameworks, automation, libraries and command line tools. Forget about The Art of Unix Programming and give the business people what they want, all the time, because the market wants now and only now and later will be too late because the market won't exist anymore.

Or, we could draw a line and say this far and no further... the line must be drawn here. Either take the time to do it right, or suffer the consequences.

How many "senior" developers, and technical leads and architects know this? How many programmers even care about these issues?

In the end we must all do things we can live with. We all have our own moral codes and standards. The choice is easy. Living with what we choose is the hard part.

Saturday, June 11, 2016

Git and GitHub in 5 Minutes for Windows

Hi,

This is Git in Five Minutes for Windows

After this, you should be able to

  • Create a git repository on the command line
  • Add files for staging
  • Commit files
  • Push files to a remote, ex. GitHub

0. Download Git for Windows Here


https://git-scm.com/download/win


1. Configure Git












git config --global user.name "Full Name Here"
git config --global user.email "Full Email Here"


2. Creating a Git Repository















git init

3. Create a File, Stage and Commit It
















echo $null >> text.txt
git status
git add .
git commit -m "Initial Commit"

4. Create a Profile and Empty Repository on GitHub






















5. Get the URL from GitHub and Push Code to GitHub













git remote add origin url
git push -u origin master (you may be prompted for GitHub login + username)

See the file successfully on GitHub!

Future Steps


1. Learn what a branch is (the whole point of DVCS - distributed version control and Git!)
2. Learn what a fork is (the whole point of GitHub!)
3. Fork an existing open source project with an issue you can solve 
  • Pick a language, or learn a language! (JavaScript / C# / Java / C++ / C / whatever!)
    • If you don't know ANY programming, play around with this then take some "intro to programming" or "learn programming" course (preferably one that's fun)
  • Start small, change one line or handful of lines of code!
4. Commit and push your change to your own fork, then issue a pull request!

???

profit

Hope this tutorial was helpful

~ B























Sunday, February 21, 2016

Advanced MVVM Concepts - MVVM Practical Theory and Experience Part 1

Hello,

This is Part 1 of short series of blog posts about practical MVVM and its usage. The goal of these posts will be to give information not readily available through documentation or examples, mainly how to construct a complex data-driven application with non-trivial issues.

This post will discuss the practical theory about MVVM and it's application in real-world applications. For theory and an introduction, look Martin Fowler's article, or look at any introductory textbook to Software Engineering/Software Architecture.

We will waste no time introducing what MVVM is and simply dive into the details (with a short refresher).

What is the Problem we are Solving?

I am not a fan of learning or increasing complexity of an application just for the sake of software purity or self-edification. Hopefully you are not either. Therefore, the question must be asked, what problems does MVVM actually solve? What is it's use? Is it worth the additional complexity? In corporate/Software Architecture parlance, what is the "use case" that MVVM applies to?

I am assuming we are solving a business problem. Business problems have a specific purpose, use and scope. In particular, we are not looking to reinvent the wheel and demonstrate technology or do technology for technology's sake (although valid reasons, we aren't talking about the technical merits here). What we are wondering is how we can solve business problems in a fast enough, maintainable enough and quick enough way that the business continues to be viable, extensible and expandable.


(wordclouds.com of Business)

So, what types of problems are we trying to solve?

1. Business problems are data problems. Data is the business, moving data from point A to point B. However, the days of simple data-entry are gone. Dumping data from the database onto the screen and saving it is a trivial, simple task. In order to create a product of any value, the relationships between data points must be maintained, because without relationships there's no meaning for the data.

2. Increasingly, data visualization is just as important as data processing. Without reports, without diagrams, without charts, without Key-Performance-Indicators, data entry is useless. This is beyond the scope of this series of blog posts, but is obviously the next step after mastering data integrity.

3. More increasingly, the interface has to be attractive enough to provide a superior user experience. Business users are now computer experts, unlike years or decades ago and expect the same experience from top-notch consumer software in their business products. Things like milliseconds of delay, buggy interactions and non-standard interactions are unacceptable. In addition, this is not the heyday of the Internet -- the market is now mature, and mature markets demand superior customer experience as the key (and sometimes only) differentiator. This is again, beyond the scope of this series of blog posts.

We will focus on problem 1, non-trivial relationships between data points. In particular, we will focus on how to represent data points with multiple relationships between data points and a hierarchical relationship (since most business problems are hierarchical) and how to create and architect software which takes this reality into account.

What does all that mean for the Developer?

In general, what that means for the bog-standard Software Developer in his day-to-day tasks is three things.

1. The primary task of a backend Software Developer (and increasingly frontend developers as well) is to create tools, or user-interfaces. This immediately directs us to some sort of design pattern (after all, UI problems are a solved problem) and immediately to MV***, *** being the question mark. The model is a given, since we are solving business problems and all business problems are modelled. The view is a given, unless we are creating backend data processing software with no user interface.

2. Unless you are lucky enough to work somewhere you can do whatever you want, you are under the gun. Particularly for a business, time is money and time is lost market-share or lost revenue. Therefore, you can't take forever reinventing the wheel from the ground up. Luckily, a lot MV*** frameworks already exist.

This is a good introduction to the differences between MVC, MVVM and MVP. In particular, we will select MVVM, because the business problems we will try to solve are non-trivial (advanced relationships between data points).

Technology

We will use technology meant to solve a business problem. This immediately leads us to -- you guessed it -- Microsoft. However, the solution we will select is KnockoutJS, the Microsoft-recommended way to accomplish advanced UI binding. However, the concepts and code samples should be clear enough to port to any framework or programming language.

The next blog post will start with a practical example of MVVM (the trivial/kitchen sink example) then discuss the problems developers immediately face when trying to implement realistic business solutions.

(Link To Be Released)

Sunday, January 3, 2016

JavaScript - Converting JSON to XML

This post discusses how to convert between a JavaScript object, XML and JSON (not the same as a JavaScript object).

(Un)Surprisingly there is no native function to do this. There's various implementations of conversion like JXON or jQuery's parseXML, but no official standard. So chances are every developer will have to work with converting between these data interchange formats (and native JavaScript objects) depending on the use case or circumstances.

JavaScript Object to JSON is the most straightforward. Just use the browser's native JSON.stringify (or use a shim if you need to support older browsers). Or is it? Consider the following case:

var obj = ["lightsaber", "blaster", "vibroblade"]

All of these are Star Wars weapons. But this data structure has no idea what's inside it. It doesn't know that these are weapons, or star wars weapons.

So the conversion then, is not trivial to XML. So care must be taken when converting between a JavaScript object and JSON, to send the metadata of the JavaScript object along.

The notation I've seen most used is the $metadata attribute. It has the added advantage of $ not being a valid XML tag character, which means you won't accidently create a node with the metadata.

So instead, obj becomes this

var obj = {
     $weapon: [
        "lightsaber",
        "blaster",
        "vibroblade"
     ]
}

The following is a sample implementation of JavaScript object to JSON



And another sample implementation of JSON to XML



Hope this gives someone ideas, or helps someone

Wednesday, November 11, 2015

Google Hangout Dial Extension

Hi,

Just wanted to add a quick note to anyone having trouble dialing an extension with Google Hangout / Google Voice

You need a working microphone plugged in and active



Without it, you won't be able to dial extension

Note that the actual dial tone doesn't have to exist. For example, when dialing an extension 3000 after dialing the number 555-555-5555, you don't hear the usual dialtone or extension sounds when dialing 3000. What you will hear is a series of clicks, but the clicks will work if there's a microphone plugged in.

Hope this helps someone

~ B

Monday, August 31, 2015

ASP.NET MVC HttpContext.Current.Server.MapPath null for WCF Webservice

Hi,

Just solved a problem at work:

If HttpContext.Current.Server.MapPath is giving you null or an exception or not working, there are several possibilities. One of them is you didn't enable asp.net compatibility mode.

https://msdn.microsoft.com/en-us/library/aa702682(v=vs.110).aspx

Better off to migrate to another way of finding the server path than depending on HttpContext though,

http://stackoverflow.com/a/6861451

HttpContext is bad to depend on, when dealing with WCF or non-MVC applications (there isn't always a context.)

Hope this helps someone

~ B

Saturday, August 8, 2015

jQuery UI Dialog Create Custom Close Button

Hi,

Just wanted to share how to create a custom close button with jQuery UI's Dialog Widget

Create a dialog this way



// TODO store modalDialog somewhere so you can call modalDialog.dialog('open'); and modalDialog.dialog('close'); when required

I suggest creating a wrapper JavaScript class, to store the dialogs by some id. That way you can retrieve dialogs already created. Some basic functions like wrapper.closeDialog(id), wrapper,createDialog(id) and so on will go a long way.

The key is, when using the .dialog function, jQuery UI wraps the dialog in its own div (the $(this).parent().find(".ui-dialog-titlebar") line).

Hope this helps someone.

Monday, July 13, 2015

ASP.NET MVC Call Controller with jQuery $.ajax and Return PartialViewResult

Hi,

Didn't find a one-stop answer to this question, so here it is:

"How do I POST JSON to an ASP.NET MVC controller?"

It's actually quite simple. Follow the following steps.

1. Create a model to represent the data structure you want to POST



2. Create a controller method to represent the endpoint you want to contact



3. Create the following jQuery call to make an AJAX call from the frontend to the backend



You can return a PartialViewResult from the controller, and as long as the jQuery AJAX call expects html it will be done.

Hope this helps someone.

Tuesday, June 30, 2015

How to call a .NET SOAP or JSON WCF Webservice with jQuery

Hi,

This is an article about how to call .NET SOAP Webservices from an HTML page. However it should be useful for anyone wanting to call any webservice from a webpage, as it outlines the technical considerations and plumbing you need to keep in mind.

There are four considerations to bear in mind

1. The type of data sent to the server and the type of data returned from the server. Consider the following,



The type of data sent to the server is XML. The type of data retrieved from the server is JSON. However, you will often want to accept / retrieve the other. Keep this in mind for the next step.

As well, if you receive XML or JSON, you will often need to deserialize into a string. Either use JavaScript's XMLSerializer or use JSON.parse to get the data you want in string format. The same goes for data you send to the server (it must be JSON.stringify or serialized into XML before sending it, not just a JavaScript string)

2. The jQuery AJAX call itself. For example consider the following

Match the content type parameter to the required input data, either 'application/xml' or 'application/json'. Note that trying 'application/soap+xml' or other unexpected content types will generate a server error in response.

3. CORS. If the HTML page is hosted on a different domain than the webservice itself (might be true in Enterprise where the webservice is on a different server than the web server) then CORS applies. Note that when using jQuery with methods other than GET, jQuery will send a preflight OPTIONS request so the server will need to accept OPTIONS and GET and POST, in addition to the appropriate CORS headers on the server side response and the HTML tags. So if you cannot control the server-side headers on your webserver, you will need a different application architecture. Perhaps call the webservice from the backend C# instead of trying to call it from the HTML.

4. The SOAP envelope. You've got three choices here

  • Retrieve the SOAP string from some external source, like a database or a text file. Every time the webservices are updated, you will have to update the external source.
  • Construct the SOAP envelope yourself with a JavaScript client. This is the approach I do not recommend, since parsing a WSDL and associated XSDs is not trivial.
  • Have a project like Apache CXF generate the SOAP client for you. This defeats the purpose of this article, since Apache CXF is a JavaScript client already. But this is an option, especially for Java backends or Enterprise.
In order to avoid these issues, have the webservice allow JSON if possible. If the architecture of the software is to allow access to the webservices from the client side (HTML pages) then the webservice should speak the lingua franca of the web (JSON) or else there's no point even exposing the webservice to the client side.

Make sure to know what type of binding the server allows, either wsHTTPBinding or basicHTTPBinding. This means a different SOAP Envelope. You may have to strip the envelope from the XML before sending it, if WCF expects only the inner request XML and not the SOAP envelope.

I hope this helps someone build their dream application. Thanks.