Sunday, 14 July 2019

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

Tuesday, 11 June 2019

Deselecting all options in HTML SELECT using Jquery plugin

I created my first jQuery plugin today. This plugin will deselect all select option elements after a given timeout when checking an associated checkbox which will in our plugin represent the $(this) object. It can be utilized when you use the data-target attribute. The data-target attribute will automatically select the first option when the checkbox is unchecked. This plugin, however - deselects all options after a given timeout of milliseconds using the setTimeout function. It will keep a pointer to the select object by applying the $() function on a passed in DOM element identifier. Example usage:
     <script type="text/javascript">
                $(function() {
                    $("[name=@SearchParametersDataContract.SomeDOMElementCheckbox]").deselectAfterSelectCheckbox("#@SomeDOMElementSelect",100);
                });
            </script>
The jQuery plugin looks like this:

        <script type="text/javascript">
            $.fn.deselectAllAfterUnselectCheckbox= function(targetSelect, timeout) {
                $(this).on("click",
                    function() {
                        if (timeout === null || timeout == undefined)
                            timeout = 50;
                        $targetSelect = $(targetSelect);
                        if (this.checked === false) {
                            setTimeout(function() {
                                 $targetSelect.children("option").attr("selected", false);
                            }, timeout)
                        };
                    });
            }
        </script>

Wednesday, 5 June 2019

Random selection of a HTML SELECT element

Just made a JsFiddle of a random selection control for HTML SELECT tag. The JsFiddle is available here: Random selecting combobox (JsFiddle)
  • The control should use Bootstrap to function properly. It needs jQuery library for Javascript bit.
  • To turn on hiding the selected option, set the data-hide-selectedoption HTML 5 data attribute to "true".

Random selecting HTML SELECT control


<!-- 
  Bootstrap docs: https://getbootstrap.com/docs
-->

<div class="container">

  <div class="input-group mb-3">
    <div class="input-group-prepend">
      <span class="input-group-text" id="basic-addon1"><img style="cursor:pointer" title="Choose random value" alt="Choose random value" width="24" height="24" src="https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-shuffle-512.png" /></span>
    </div>
    <select data-hide-selectedoption="true" disabled id="ComboBoxIceCreamBar" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1">
 <option selected hidden>Choose icecream</option>
 <option value="Vanilla">Vanilla</option>
 <option value="Strawberry">Strawberry</option>
 <option value="Pineapple">Pineapple</option>
 <option value="Mint chocolate">Mint chocolate</option>
 <option value="Mango ice cream">Mango ice cream</option>
 <option value="Rasperry Ripple">Raspberry Ripple</option>
 <option value="Pistachio">Pistachio</option>
 <option value="Cookie dough">Cookie dough</option>
 <option value="Lemon">Lemon</option>
 <option value="Mango">Mango</option>
 </select>
    <!-- <input type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1"> -->
  </div>

</div>

<script type="text/javascript">
  $("#basic-addon1").on("click", function() {
    var selectcontrol = $(this).parent().siblings('select:first');
    var optionslength = selectcontrol.children('option').length;
    var randomIndex = Math.max(1, parseInt(Math.random() * optionslength));
  var optionElementToSelect = selectcontrol.children('option')[randomIndex];
    optionElementToSelect.selected = true;
  //debugger
  if (selectcontrol.data('hide-selectedoption')){
       optionElementToSelect.innerText = 'Selected value hidden.';   
  } 
  console.log("Selected ice cream: " + selectcontrol.val());
  });

</script>