Monday, 15 July 2019

Http echo service written in Node.js

I have added a small repo on Github that shows how to create a simple HTTP echo service. https://github.com/toreaurstadboss/NodeJsHttpEchoServer The server.js is script is this:
let http = require('http');

console.log('Attempting to start the Node.js echos server on port 8081..')
http.createServer().on('request', function(request, response){
 request.pipe(response);
}).on('close', function(){
    console.log('The Node.js echo server has been closed.')
})
.listen(8081);

console.log('Node.js echo server started on port 8081.')

This will pipe out the requesting data to the response. Test it out with this command for example in a command window: curl -d "Hello dog" http://localhost:8081 Note - use not Powershell for this command as Powershell has aliased curl command for Invoke-WebRequest. Rather install curl with Chocolatey for example, choco install curl

Sunday, 14 July 2019

Using Ndepend to investigate method cycles

Ndepend is a very powerful Code analysis platform for DotNet and I have created a method cycle detection rule. The method cycle detection also supports property setters and getters. A cycle in a property or method will often cause problems, such as stack overflow exceptions due to too many recursive calls. Spotting such cycles can often be hard in real-world scenarios. A classic error is to actually do a cycle through a property getter, by just calling the getter once more or a property setter for that instance. The following C# attribute invokes a Rules extracted from Source code from Ndepend.

using System;
using NDepend.Attributes;

namespace Hemit.OpPlan.Client.Infrastructure.Aspects
{

    /// <summary>
    /// Ndepend attribute to enable cyclic loops in methods in the source code 
    /// </summary>
    [CodeRule(@"// <Name>Avoid methods of a type to be in cycles. Detect also recursive property setter calls</Name>
warnif count > 0

from t in Application.Types
                 .Where(t => t.ContainsMethodDependencyCycle != null && 
                             t.ContainsMethodDependencyCycle.Value)

// Optimization: restreint methods set
// A method involved in a cycle necessarily have a null Level.
let methodsSuspect = t.Methods.Where(m => m.Level == null)

// hashset is used to avoid iterating again on methods already caught in a cycle.
let hashset = new HashSet<IMethod>()


from suspect in methodsSuspect
   // By commenting this line, the query matches all methods involved in a cycle.
   where !hashset.Contains(suspect)

   // Define 2 code metrics
   // - Methods depth of is using indirectly the suspect method.
   // - Methods depth of is used by the suspect method indirectly.
   // Note: for direct usage the depth is equal to 1.
   let methodsUserDepth = methodsSuspect.DepthOfIsUsing(suspect)
   let methodsUsedDepth = methodsSuspect.DepthOfIsUsedBy(suspect)

   // Select methods that are both using and used by methodSuspect
   let usersAndUsed = from n in methodsSuspect where 
                         methodsUserDepth[n] > 0 && 
                         methodsUsedDepth[n] > 0 
                      select n

   where usersAndUsed.Count() > 0

   // Here we've found method(s) both using and used by the suspect method.
   // A cycle involving the suspect method is found!
   let cycle = ExtensionMethodsEnumerable.Append(usersAndUsed,suspect)


   // Fill hashset with methods in the cycle.
   // .ToArray() is needed to force the iterating process.
   let unused1 = (from n in cycle let unused2 = hashset.Add(n) select n).ToArray()

let cycleContainsSetter = (from n1 in cycle where n1.IsPropertySetter select n1).Count()

  
select new { suspect, cycle, cycleContainsSetter }",
        Active = true,
        DisplayStatInReport = true,
        DisplayListInReport = true,
        DisplaySelectionViewInReport = true,
        IsCriticalRule = false)]
    public class MethodCycleDetectionAttribute : Attribute
    {
    }
}


Note that this Ndepend Code rule uses the CQLinq syntax placed into a C# attribute class that inherits from Attribute and itself is attributed with a Ndepend.Attributes.CodeRuleAttribute. I had to adjust the attribute a little bit using the ExtensionMethodsEnumerable fix for .Net 4.6.2 mentioned on Ndepend blog post here: https://blog.ndepend.com/problem-extension-methods/ The following screen shot shows Visual Studio 2019 with Ndepend version 2019.2.5 installed. It shows the method cycle detection code rule I created showing up as a code rule through source code. Selecting that code rule in the menu Ndepend => Rules Explorer that selects Queries and Rules Explorer allows to not only view the code rule but quickly see the code analysis results.
One method cycle I have is shown in the following image, the method ProcessPasRequest of my system. This case shows how advanced Ndepend really is in code analysis. It can detect transitive cycles with multiple function calls. The following two screen shots shows the cycle in question. In this case, it was not a bug, since the cycle will only happend a finite amount of times for a given set of patients, but it still can go into an infinite loop if the external system is not working correct. However in this case, if that external system is not working, the system I have been working with also faults as it relies on that external system. With Ndepend I could spot method cycles with transitive cycles with a breeze! I can also spot property getter and setter cycles, as property getters and setters in C# are methods anyways (compiler generated). I managed to get Ndepend back to the main menu in Visual Studio 2019 using this extension.
https://marketplace.visualstudio.com/items?itemName=Evgeny.RestoreExtensions

Loading tweets from Twitter with Node.Js and Express.Js

This article will present a Git repository I created that can fetch tweets from Twitter using Twitter Api v1.1 and Node and Express. Or also known as Node.js and Express.Js. First off, Twitter now enforces all API calls to be authenticated. To be able to call the Twitter API, there are four values you must retrieve for the App you have created at https://developer.twitter.com/en/apps. These are:
  • Consumer API
  • Consumer API secret
  • Access token
  • Access token secret
The Git repo I created is available here: https://github.com/toreaurstadboss/SimpleTwitterFeedExpressJs The solution is started using: npm run start But for working with the solution, use nodemon command. The server.js is the primary part. Here we create the Express.Js server object for Node which will host our web service calls for the Tweets. We use the following Npm libraries:
  • express (web server)
  • fs (FileStream for Node
  • https (for secured communication
  • Twitter (for Twitter API v1.1 communication
The following Js script is the server.js file:
var express = require("express");
var request = require("request");
let config = require("./config");
const https = require("https");
const fs = require("fs");
var url = require("url");
var Twitter = require("twitter");

var key = fs.readFileSync(__dirname + "/certs/selfsigned.key");
var cert = fs.readFileSync(__dirname + "/certs/selfsigned.crt");
const port = 3000;
var options = {
  key: key,
  cert: cert
};

var app = express();

var client = new Twitter(config);

app.get("/", function(req, res) {
  res.sendFile(__dirname + "/index.html");
});

function getTweets(userName, tweetCount, res) {
  var params = {
    q: userName,
    count: tweetCount
  };

  var responseFromTwitter = {};

  let tweetSearched = false;

  // Initiate your search using the above paramaters
  client.get("search/tweets", params, function(err, data, response) {
    console.log("Found # Tweets: " + data.statuses.length);
    res.charset = "utf-8";
    res.append("Content-Type", "application/json; charset=utf-8");

    // If there is no error, proceed
    if (!err) {
      res.end(JSON.stringify(data.statuses));
    }
  });
}

app.get("/tweets/:username", function(req, res) {
  let tweetsFound = getTweets(req.params.username, 10, res);
  console.log(tweetsFound);
});

app.use("/css", express.static(__dirname + "/node_modules/bootstrap/dist/css"));

var server = https.createServer(options, app);
server.listen(port, () => {
  console.log("server starting on port: " + port);
});
Make note that this sample uses HTTPS communication. It is using self signed certificates. I created these using this command inside Windows Subsystem for Linux: sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ./selfsigned.key -out selfsigned.crt This created the key pair of the selfsigned key and the certificate. The HTTPS server is created using this:
var server = https.createServer(options, app);
server.listen(port, () => {
  console.log("server starting on port: " + port);
});
The bulk of the code retrieving the Tweets is the method getTweets. We pass on the response object and use the end method of Express to stringify the JSON data we found. I have not done much error handling here. We return data as Json if we found some Tweets for given username. There is one route defined in Express here: app.get("/tweets/:username", function(req, res) { let tweetsFound = getTweets(req.params.username, 10, res); console.log(tweetsFound); }); The method getTweets will then retrieve data from Twitter using a HTTPS call to
function getTweets(userName, tweetCount, res) {
  var params = {
    q: userName,
    count: tweetCount
  };

  var responseFromTwitter = {};

  let tweetSearched = false;

  // Initiate your search using the above paramaters
  client.get("search/tweets", params, function(err, data, response) {
    console.log("Found # Tweets: " + data.statuses.length);
    res.charset = "utf-8";
    res.append("Content-Type", "application/json; charset=utf-8");

    // If there is no error, proceed
    if (!err) {
      res.end(JSON.stringify(data.statuses));
    }
  });
}

To test out this code, you can enter the following command to clone the repository.
git clone https://github.com/toreaurstadboss/SimpleTwitterFeedExpressJs.git