Sunday 10 November 2019

Implementing projection in Javascript

Github page for source code in this article:
https://github.com/toreaurstadboss/JsLinqSimpleProjection
https://www.npmjs.com/package/jslinqsimpleprojection
Npm package for source code in this article: Since I started working with Linq in C#, I missed a good way of doing much of the same functionality in Javascript. Today, there are several Linq libraries for Javascript and Typescript, and libraries such as Backbone.Js or Lodash also containing a lot of helpful operators or utility methods. As an educational exercise, I was looking into a simple way of doing a projection method in pure Javascript (no es6 syntax). Here is what I made. First off, we need to be able to project an array of objects by listing up properties. In ES6 Javascript we could use arrow functions. But I wanted to support pure Javascript. So I choose to use a comma separated list of property or field values to dive into the array object, written in Json notation of course. Consider first this array as an example:

        var someCountries = [
          { country: "Norway", population: 5.2, code: "NO" },
          { country: "Finland", population: 5.5, code: "SU" },
          { country: "Iceland", population: 0.4, code: "IC" },
          { country: "Sweden", population: 10.2, code: "SW" }
        ];

We want to project this array using a new method select on the array of which we use the Array.prototype to achieve. Note that this will immediately add methods to all array objects immediately in the global scope. Now consider a projection of just the 'country' and the 'population' fields of the Json structure. Given a method call of just these two properties, we want to create a select projection method. First consider this lightweight linqmodule implementation, using an IFE (Immediately invoked function expression) and using the revealing module pattern. We expose the method dump to this module.

var linqmodule = (function() {
  projection = function(members) {
    var membersArray = members.replace(/s/g, "").split(",");
    var projectedObj = {};

    for (var i = 0; i < this.length; i++) {
      for (var j = 0; j < membersArray.length; j++) {
        var key = membersArray[j];
        if (j === 0) {
          projectedObj[i] = {};
        }
        projectedObj[i][key] = this[i][key];
      }
    }

    return projectedObj;
  };
  Array.prototype.select = projection;

  dumpmethod = function(arrayobj) {
    var result = "";
    result += "[";

    for (var i = 0; i < Object.keys(arrayobj).length; i++) {
      var membersArray = Object.keys(arrayobj[i]);
      for (var j = 0; j < membersArray.length; j++) {
        if (j === 0) {
          result += "{";
        }
        var key = membersArray[j];
        result +=
          "key: " +
          key +
          " , value: " +
          arrayobj[i][key] +
          (j < membersArray.length - 1 ? " , " : "");
        if (j === membersArray.length - 1) {
          result +=
            "}" + (i < Object.keys(arrayobj).length - 1 ? "," : "") + "\n";
        }
      }
    }
    result += "]";

    return result;
  };

  return {
    dump: dumpmethod
  };
})();


Now it is easy to dump the contents of our projected array (which is copied into a new object) using the dump method:

 result = someNums.select("country,population");
         document.getElementById("result").innerText = linqmodule.dump(result);

        console.log(result);

Note that our new object contains only the country and population fields in the Json structure, not the code. We have created a simple projection mechanism in Javascript in a self contained module!

Arithmetic parser in Javascript

I just added an arithmetic parser in Javascript code sample on Github, check out the following repo: JsSimpleParser The parser is also available through Npm: https://www.npmjs.com/package/simplejsparsermatharithmetic Installation: npm i simplejsparsermatharithmetic Supported expressions (examples): 2+3 should evaluate to 5 12 * 5–(5 * (32 + 4)) + 3 should evalute to -117 This is a great example of how to write a parser of your own.

Sunday 13 October 2019

Using TagBuilder in MVC

I have been started programming MVC again at work after many years focusing more on WPF. So I came accross a class called 'TagBuilder'. This is a handy class for generating markup programatically. Let us create a HTML helper that renders an image tag. It can use TagBuilder to achieve this. First off, we create the HTML helper like this:
using System.Web;
using System.Web.Mvc;

namespace HelloTagBuilderDemo.Helpers
{
    /// <summary>
    /// Sample usage of TagBuilder in MVC
    /// </summary>
    public static class HtmlHelpers
    {
        /// <summary>
        /// Generates an IMG element which is self-closing and uses as src the given path pointing to an image file with a relative path within the web application
        /// and with alternate text
        /// </summary>
        /// <param name="path"></param>
        /// <param name="alternateText"></param>
        /// <returns></returns>
        // ReSharper disable once UnusedParameter.Global
        // ReSharper disable once InvalidXmlDocComment
        public static IHtmlString Image(this HtmlHelper htmlHelper, string path, string alternateText)
        {
            var builder = new TagBuilder("img");
            // ReSharper disable once StringLiteralTypo
            builder.Attributes.Add("src", VirtualPathUtility.ToAbsolute(path));
            builder.Attributes.Add("alt", alternateText);
            var markupResult = builder.ToString(TagRenderMode.SelfClosing);
            return new MvcHtmlString(markupResult);
        }
    }
}

We make use of the VirtualPathUtility.ToAbsolute method to convert a virtual path to an absolute path. Then we make use of the html helper inside a MVC view like this:

@{
    ViewBag.Title = "Home Page";
}

@using System.Web.Mvc.Html
@using HelloTagBuilderDemo.Helpers


<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>

<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <p>Harold is at it again, making clones of himself to inflict multiple pain.</p>                
    </div>
    <div class="col-md-4">
        @Html.Image(@"~/Images/haroldatitagain.jpg", "Harold")
    </div>
</div>
And now we have our resulting HTML helper at display, showing also in the screen grab the markup the HTML helper generated for us. [1] Tagbuilder on MSDN: https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.tagbuilder?view=aspnet-webpages-3.2