Posts by Philip Munce

  • Create your own ContosoPizza using replit

    I like using replit as my personal code editor mainly because of the convenience of an online editor. I thought it would be neat to show you how you can follow along with a tutorial from Microsoft to build a ASP.NET Core REST web site.

    I am following the tutorial from here:

    First thing I did was log on to replit and then create a new C# repl called ContosoPizza.

    This isn’t ready yet for running a web site as it only generates a console application but I can then make some changes to the structure of the repl to create a new ASP.NET project that will run the tutorial from the Microsoft learning web site.

    Each repl will come with a console which will let you run most unix commands and if you cannot run a command the repl comes with a full unix shell as well to do some more complicated unix stuff. Personally I prefer not to jump into the unix shell unless I really need to and for what we are doing the console will provide enough functionality.

    To create a dotnet project it is pretty simple, just go to the console and run this command: dotnet new webapi -f net6.0

    This will setup a new web api project but if you click run on the repl you will get an error like the following:

    Specify which project file to use because /home/runner/ContosoPizza contains more than one project file.

    The reason for that is simple you have two project files in your root folder. To fix that delete the file main.csproj and the file main.cs. You can then run the repl but you cannot do a lot as the repl is running on ports that are not exposed outside of your repl virtual machine. Again this is simple matter to fix, simply open the file Properties/launchSettings.json and change the applicationUrl for ContosoPizza to “”. When you click run you will see a blank screen, and you can now see the results at this url:

    So to recap, what I have done is to create a new C# repl using called ContosoPizza. I then ran the dotnet sdk to generate a new web api project and removed the initial main.cs and main.csproj files so the project can run. Finally I changed the launch settings to use so that the project could be exposed via the replt web site.

    This is the contents of my launchSettings.json

      "$schema": "",
      "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
          "applicationUrl": "http://localhost:32264",
          "sslPort": 44303
      "profiles": {
        "ContosoPizza": {
          "commandName": "Project",
          "dotnetRunMessages": true,
          "launchBrowser": true,
          "launchUrl": "swagger",
          "applicationUrl": "",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        "IIS Express": {
          "commandName": "IISExpress",
          "launchBrowser": true,
          "launchUrl": "swagger",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"

    Helpful links:

  • Good article on building a REST API using Sqlite

  • New gig on Fivvr

    I am available for work on Fivvr see:

    The details are below:

    The new WordPress Block Themes lets you implement a WordPress theme using the Gutenberg Block Editor. I can implement a WordPress theme for you built using the Block Theme. 


    • Your own block theme using out of the box components 
    • Code available for you in a GitHub repository 
    • Customizations, plugins and shortcodes 
    • Contact forms 
    • Google analytics link 
    • Responsive and mobile friendly themes 
    • Site is editable using WordPress dashboard 

    Please contact me for a detailed quote for implementing your requirements. 

  • Connecting WordPress plugin to active directory (Microsoft AD)

    Connecting a WordPress plugin to Microsoft Active Directory involves writing code to perform a HTTP POST to a Microsoft authentication endpoint.

    I have put the code for doing this in PHP below and once you have copied this into your plugin you can use the code to retrieve an access token for use in making future API calls to Microsoft hosted resources.

    class TC_AD_Service {
    	static function getAccessToken($tenant_id, $client_id, $client_secret) {
        $client = new GuzzleHttp\Client();
        $url = '' . $tenant_id . '/oauth2/v2.0/token';
        $response = $client->request('POST', $url, [
          'verify' => false,
          'form_params' => [
            'grant_type' => 'client_credentials',
            'client_id' => $client_id,
            'scope' => '',
            'client_secret' => $client_secret        
        $body = $response->getBody();
        return json_decode($body);

    I have made use of the GuzzleHttp library which is a PHP library for making HTTP calls. The library was imported using composer and I use the library to submit a HTTP post to the endpoint.

    The URL I used consists of the tenant id which is id of an application registered in Microsoft Active Directory and the Microsoft endpoint to request an OAuth token.

    I pass to the endpoint the client id and client secret which I configured in Active Directory along with the powerbi scope.

    Finally I return back a PHP object read from the response body and containing the access token and the access token expiry date.

  • About Azure App Service (from 2015)

    Tom Archer ( continues the discussion around the new Azure App Services by detailing how they relate to the existing set of Azure services. In his article on the Microsoft Azure site ( he explains the different types of services available now under the Azure App Services umbrella which are:
    • Web Apps (migration from existing Azure Websites)
    • Mobile Apps (migration from existing Mobile Services)
    • API Apps (new type of App specifically designed for Micro Services
    • Logic Apps (new type of App with BPM workflows in mind)
    • BizTalk API Apps (exposing BizTalk capabilities as API’s, migration from the current Azure BizTak Services).

  • Install Node.js and Cygwin

    1. Install cygwin at:
    2. Install node.js at
    3. Install git at
    4. Create the sample, hello.js
    5. Follow the instructions here to create a new project and upload to azure

    According to

    Node.js® is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

  • Using Swagger to describe an API

    Microservices and Pace Layering

    Micrososervices Architecture

    There is a lot of hype around at present for API’s or Microservices. This is a good thing because they represent a new way of looking the SDLC by breaking down applications into smaller more manageable pieces. Martin Fowler sums it up well at by highlighting the differences between traditional monolithic applications and Microservices.

    Microservices appear to be a concrete implementation of the abstract concept of pace layering put forward by Gartner to solve emerging platforms for IT delivery ( The monolithic applications may stay around as systems of record but new ways are needed to manage systems of differentiation and systems of innovation.  My current thinking around Microservices is they enable the exposure of corporate data in new innovative ways and also allow corporations to look at ways of exposing themselves into customer processes rather than driving customers into their processes.

    Defining an API

    Anyway the above would make a great blog post but tonight I am looking at how to define part of the business  requirements for using Microservices. In this case it is looking at how to define technical requirements or an API specification. An API specification is a descriptive document that defines the expected inputs and outputs for a Microservice which is exposed as a Web API call typically for invocation via a HTTP/REST request.

    The goal of creating an API specification is to be descriptive and not proscriptive and to define an endpoint that someone can create a client for and call. I think it is important to be descriptive and to describe exactly what needs to be provided but also what is expected to come out of an API request.  What I like about doing this is that it allows me to concentrate solely on the customer experience at first and design the solution based on how the software will be used rather than what an end system requires.

    The Example – Blog Post Routing

    To give this a concrete example, what I would like as an active blogger to be able to use an API request to publish blog articles from my phone and also from Microsoft Word or Excel.  A requirement for this is to have a well defined endpoint that exposes enough fields and capabilities that I am able to create a post in an editor of choice, create images, and submit to an API for routing to the blogging platform of choice. In this case there are two blogs, one is this blog ( and the second is an internal company blog for my employer ( I use my personal blog to record my current learning’s about technology and to elicit feedback on my thought bubbles. For work I need to capture project progress and decisions and also put up reference information.


    So that I can describe the API I need a language. In this case I am using Swagger ( but there are others such as WADL which is the REST equivalent of WSDL.  Swagger is promoted as a way of documenting ASP.NET Web APIs ( and also has the benefit of providing a free online editor (  Swagger uses a language known as YAML which stands for yet another markup language and is similar to JSON in that it is designed to be machine and human readable.

    Defining API for Business Processes

    When defining the API I started by considering what the basic use case was. In this case it involves a person (i.e. myself) submitting a request to upload a blog post.  This will eventually be done by calling the WordPress API ( and the Confluence equivalent. But I don’t want to have to necessarily remember how to submit to both all the time plus there is a marketplace being built for Azure Web API’s that should have an exposed API for making the physical blog posts.  What I would do then is to provide a common interface for any blogging platform allowing for a new post to be submitted. For me to effectively do this what I can do is change my thinking from being system centric to being business process centric. This simply means that I think in terms of business processes and business process objects.  A business process is something (set of tasks, decisions etc) that delivers value to a customer, a business process object is a document going through state changes as part of the process.  In this case the business process is blogging or knowledge sharing. The value is improved knowledge both for myself and readers and the process object is the blog post itself.

    One thing that is interesting about business processes is that they have a lifecycle both for the process and the object. In the case of the blog post a rough lifecycle is conceptualization (or discovery), followed by scribing and analysis, followed by submission, followed by formatting, followed by pruning, followed by reviewing and moving back into conceptualization. Like a lot of lifecycle methodologies this roughly correlates to the Plan, Do, Check, Act cycle.  What this means for the API is that because the blog post could be thought of as ‘alive’ the planning for API calls needs to take the lifecycle into consideration and a rough sequence of events is given below along with the anticipated capabilities needed to support the lifecycle.

    • Conceptualization – diagramming, searching,
    • Scribing and analysis – clipping tools, screen captures, scrapbooks, saving pages
    • Submission – blog posting, multi platforms and devices, templates
    • Formatting – template to blog format, images and attachments
    • Pruning – easy updating, keyword analytics
    • Reviewing – comments, social promotion, comparisons to other knowledge
    • … (back to conceptualisation for next blog post)

    Content Office API

    For the v1.0 API endpoint the blog post can be assumed to be in a simple format containing content which is either paragraphs, lists (numbered and ordered) and headings.  More complicated content can be supported in subsequent versions of the API.  The process object in this case is a blog post, which I am abstracting up to the more generic term of ‘Article’ in line with the HTML5 specifications.  The hierarchy for an article is: Content -> Article which means that I want to use the term Content in the API definition and the term Article as the process object inside the API.  The API itself then is called the Content Office API to reflect that the API supports a business process very similar to building a set of articles as content for a newspaper in an office (actually I wanted Content Foundry but someone has already taken that name,

    Using Swagger options

    To get started using Swagger I went to the web page and scrolled down to the ‘Swagger tools & Resources” section.  Under the ‘Swagger Editor’ section I then selected the Demo option. example

    This brought up a great looking editor with an example YAML file for the Swagger Petstore as an example. example

    What I then did is replace references to pet with references to article and articles to build up an API request to POST a new article to the API for submission.

  • Handcrafting Swagger

    What is Swagger

    Swagger is a new way of defining API or web service endpoints currently being maintained by SmartBear the makers of SoapUI.  The concept is to provide an easy way of describing what an API does which is readable both by humans and by machines.  I want to in this post walk through a handcrafted approach to defining an API using the swagger syntax.

    Creating a Swagger File
    I have created a minimal swagger.json file below showing settings that will form a basic file.  In this case I have created a title and a plain english description and have defined the host for the API which will run of my personal hosting for now.

    "swagger": "2.0",
    "info": {
    "version": "1.0.0",
    "title": "Blog Updater API",
    "description": "This API is called to update one or more blogs with specified content.",
    "termsOfService": "",
    "contact": {
    "name": "API Support",
    "url": "",
    "email": ""
    "license": {
    "name": "Apache 2.0",
    "url": ""
    "host": ""

    Generating API Documents
    I downloaded the swagger UI from and copied the contents of the dist folder into a local folder on my PC. I then put the swagger.json file above into the folder.  If you have python install on your PC you can take advantage of the simple HTTP server which python provides. To do this I opened a command prompt, changed directory to the local folder with the swagger ui and typed “python -m http.server”. This started a basic HTTP server on my PC. I then opened http://localhost:8000 in my browser and after entering http://localhost:8000 got the first look at my API as documentation.

  • How I was able to configure syntax highlighting on my WordPress site

    I like to blog about technical topics and part of this involves providing code snippets with an explanation and further exploration about those code snippets.

    When readers are reading a page on my blog I would like any code snippets that are on a page to be formatted with syntax highlighting as per the following image:

    The WordPress Gutenberg editor provides a code block which will be used to output HTML tags which are typically used to hold a code snippet.

    The problem is that the HTML code block does not have any specific formatting and will require changes to be made to the contents of the code block in order to display with syntax highlighting. The changes are to identify key words in a code snippet and then put <span> tags around those keywords with a specific class applied to each. This can be done fairly easily with a regular expression search applied across a small block of code.

    I made a decision that I would use a code library to implement this functionality rather than write my own library. I decided to use the Code Prettify library from the Google archives in GitHub. I haven’t used this library before but according to the readme on the github page for code-prettify it is used to power and which is encouraging.

    The code-prettify library can be found here:

    And to use the library once it is installed on a page what I need to do is to put a class=”prettyprint” on the pre or code tags on my page:

    Now typically you would do this I guess in the functions.php file by providing a content hook and I am thinking in the future I might do this. But for the moment I am applying this functionality through a global search and replace in my client side react code.

    function formatPost(post) {
      const rendered = post.content.rendered;
      let result = rendered.replace(/\<code\>/g, '<code class="prettyprint">');
      const parsed = parse(result);
      return parsed;

    As you can see from the code snippet (hopefully highlighted) above the logic to apply syntax highlighting has now shrunk down to a single line regular expression. The content for each post is returned inside a post.content.rendered string when retrieved via the REST API. So what the formatPost function will do is take that string and apply any client side formatting before the contents of the post are rendered on the page. I should also mention that I am using a react library to convert the post.content.rendered string into a react object for rendering on the page. This library is the react-html-parser.

    The above code of course will only run if I have included a link to the code-prettify library on my HTML page. For WordPress sites this is typically done using the wp_enqueue_script function call. My first call when linking to a third party library now is to use a CDN. I find that this is a stable and fast way to bring libraries in and also means you should be on a later version.

    According to the instructions on the git hub page for code-prettify I need to include a script tag in my document as follows:

    Because I am using a WordPress theme I use the following code inside the script_loader_tag hook to add the run_prettify.js file on each page as a linked Javascript library.

        wp_enqueue_script( 'code-prettify', '' );

    Finally if you are more of a content creator than a developer then you may want to link to a plugin to achieve the above functionality. I have found this Code Prettify plugin on the WordPress plugins directory which uses the code-prettify library and might help you if you would like syntax highlighting on your site.

  • I have updated my WordPress REST API to set and return the number of views per post

    The next iteration or feature I have implemented in my react theme is a view counter which shows the number of views each one of my posts is getting on my WordPress site. The number of views is a number value that is held against each post on my WordPress site using what is known as post meta. Post meta is a mechanism that WordPress provides that will let you store some additional data with each post and is normally set behind the scenes for you by custom PHP code running in either a theme or a plugin.

    In my case I have set up a filter inside my functions.php file to increment a post views value by 1 each time a request is made to retrieve data for a specific post via the Rest API. The Rest API is a handy out of the box feature that WordPress provides that will let you access your pages and posts as a JSON string. You can try this out by appending /wp/v2/posts/ to the end of your site URL. You can read more information about the Rest API by going to this site: With WordPress programming what you often need to do is search and find an appropriate hook.

    I was not able to find an exact hook for what I wanted to do which is to be able to run some custom code when a user requests a single post via the WordPress API. There are some hooks available for when a post is processed for sending to the user but these hooks also ran when the list of posts were retrieved which isn’t ideal particularly as I couldn’t find an easy way to distinguish between a single post and a list of posts.

    So what I found was there is a hook called rest_request_before_callbacks which as the name suggest runs before further processing of a rest request occurs. The documentation for this hook can be found here: I feel that there will be a job for future Phil to use another hook or write a custom post handling class but for now this hook works quite well.

    Currently my code for this hook looks like the following:

    function my_react_count_views( $response, $handler, WP_REST_Request $request ) {
        $id = $request->get_param('id');
        $route = $request->get_route();
        if ((stristr($route, 'posts') || stristr($route, 'pages')) && isset($id)) {
            $views = get_post_meta($id, 'post_views', true);
            if (!$views) {
                add_post_meta($id, 'post_views', 1);
            } else {
                update_post_meta($id, 'post_views', intval($views) + 1);
        return $response; 
    add_filter( 'rest_request_before_callbacks', 'my_react_count_views', 10, 3 );

    I will walk through the code step by step for you.

    The first thing I do is attempt to get the id parameter for the post or page by looking for an id in the page parameters using $request->get_param(‘id’);. This of course will not work in the future when I move to permalinks but in the interests of getting the work done I have taken this approach for now. I haven’t looked too far into how to get this working with permalinks rather than id’s but I have a feeling the concept will be the same, I will just replace looking for an id with looking for a permalink. The reason for doing this is that I needed something to distinguish between someone viewing a post on a page and someone viewing a list of posts. In my original version I was finding that the counter was increasing each time I viewed the list.

    The next step is to check that the route contains either posts or pages by using the PHP stristr function.

    So this means that for pages or posts with an id I want to then check the post meta by using the WordPress get_post_meta function. This function will either return a value or null. If the value is null I use add_post_meta to assign a value of 1 to the post_views and if the value is set (i.e. > 0) then I use update_post_meta to store an incremented by 1 value into my WordPress site.

    You can view this working on my personal site, by clicking on a post:

    The post_views counter is available in the Network tools – Preview tab in Chrome, Edge or Brave. You can see that the post_views is returned as part of the meta element and can then be used inside my theme by the React code to render the counter.

    In a future post I will show how I used this value inside my React WordPress theme to render the view using Javascript.