Posts by Philip Munce

  • Good article on building a REST API using Sqlite

    https://geshan.com.np/blog/2021/10/nodejs-sqlite/#sqlite-and-node.js


  • New gig on Fivvr

    I am available for work on Fivvr see: https://www.fiverr.com/s2/9c01831702

    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. 

    Services 

    • 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.

    <?php
    class TC_AD_Service {
    	static function getAccessToken($tenant_id, $client_id, $client_secret) {
        $client = new GuzzleHttp\Client();
        $url = 'https://login.microsoftonline.com/' . $tenant_id . '/oauth2/v2.0/token';
        $response = $client->request('POST', $url, [
          'verify' => false,
          'form_params' => [
            'grant_type' => 'client_credentials',
            'client_id' => $client_id,
            'scope' => 'https://analysis.windows.net/powerbi/api/.default',
            '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 login.microsoftonline.com 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 (https://github.com/TomArcher) 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 (http://azure.microsoft.com/en-us/documentation/articles/app-service-changes-existing-services/) 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: http://cygwin.com/install.html
    2. Install node.js at nodejs.org
    3. Install git at http://git-scm.com/
    4. Create the sample, hello.js
    5. Follow the instructions here to create a new project and upload to azure http://azure.microsoft.com/en-us/documentation/articles/web-sites-nodejs-develop-deploy-mac/

    According to nodejs.org:

    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 http://martinfowler.com/articles/microservices.html 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 (http://www.gartner.com/newsroom/id/1923014). 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 (philipmunce.wordpress.com) and the second is an internal company blog for my employer (www.mexia.com.au). 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.

    Swagger

    So that I can describe the API I need a language. In this case I am using Swagger (http://swagger.io/) 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 (http://bitoftech.net/2014/08/25/asp-net-web-api-documentation-using-swagger/) and also has the benefit of providing a free online editor (http://editor.swagger.io/?#/).  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 (http://wp-api.org/) 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, http://contentfoundry.net/).

    Using Swagger

    swagger.io options

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

    swagger.io.petstore example

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

    swagger.io.articles 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": "http://homesite.munceyweb.com/api/blogupdater/terms/",
    "contact": {
    "name": "API Support",
    "url": "http://homesite.munceyweb.com/api/blogupdater/support",
    "email": "api.support@munceyweb.com"
    },
    "license": {
    "name": "Apache 2.0",
    "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
    }
    },
    "host": "http://munceyweb.com"
    }

    Generating API Documents
    I downloaded the swagger UI from https://github.com/swagger-api/swagger-ui 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 https://code.google.com/ and http://stackoverflow.com/ which is encouraging.

    The code-prettify library can be found here:

    https://github.com/googlearchive/code-prettify

    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.

    https://www.npmjs.com/package/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', 'https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js' );
    

    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: https://developer.wordpress.org/rest-api/. 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: https://developer.wordpress.org/reference/hooks/rest_request_before_callbacks/. 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, https://munceyweb.com 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.


  • Adding view counter to wordpress rest api

    This snippet of code will add a view counter to your wordpress rest api, making the value available in the meta->post_views field for future use.

    /**
     * Updates the post meta with a views counter
     */
    function my_react_rest_prepare_post($response) {
        if (!isset($response->data) && isset($response->data['type'])) return $response;
        if ($response->data['type'] == 'post') return $response;
        $id = intval($response->data['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;
    }