ASP.NET MVC 5: OWIN/Katana Pipeline And Middleware Components (A Demo)

DEMO | CODE | MY (Other) PROJECTS

If you know ASP.NET Core, you will notice some similarities between that and Katana.  That is because both of them supports OWIN: Katana bringing OWIN support to ASP.NET; and ASP.NET Core natively supporting OWIN.

In this demo, using ASP.NET MVC 5, I registered my OWIN middleware components in the Configuration(IAppBuilder) method of the Startup class declared in Startup.cs by calling one of the these methods: IAppBuilder.Use(), or an IAppBuilder extension method that wraps IAppBuilder.Use(),  or IAppBuilder.Run().  This code explains it a little bit more.

I declared all my OWIN components in a separate file named Startup.MyOWINComponents.cs.  Each component adds a Hello World!!! string in their own language to an OWIN environment variable and awaits the next component in the pipeline, and once the last component is done it passes control back to the previous component until the first component in the pipeline outputs the resulting string to response.  This code explains it a little bit more.

The demo displays the following:

Hello World!!!
Bonjour Tout Le Monde!!!
Mabuhay!!!

 

Advertisements

AI, Anyone?


Recently got interested in AI, particularly how far it has gone.  Now I’m wondering if we are close to having the ultimate AI that closely resembles a human being.  I have some background on AI (well sort of) during my university days a long time ago :).  I did work on a thesis on fingerprint recognition that requires advanced math skills (e.g. Fourier transforms, etc.) but good thing there is already an IBM PC that time to do that for you.  I also met someone doing his Masters thesis using neural networks to train a computer to just check a multiple choice exam.  If I remember it right, he is using the back propagation algorithm.  Don’t quote me on these, I never did try to understand all these stuff at that time, plus it’s actually advance to me.  Fast forward today I see there are already a bunch of algorithms that were created and different ways to train an AI and I would be interested to check them out and see for myself if I can create my own AI that I can train from baby stage to adult stage.  I have this opinion that it will take years to train an AI just like how we humans learn.  I think in an AI, there are many different areas that a machine learning need to be applied.  Ultimately, an AI needs to learn how to learn all these stuff.

So I started this post just to compile my findings on the latest technologies / tools related to AI.  So far here are some of them and I will continue to update this as I discover more.

  • A cheat sheet listing all there is right now in AI, Neural Networks, Machine Learning, Deep Learning & Big Data.  It will give you an idea on what has been done or currently being done.
  • A program in Python implementing neural networks.  Mind you this is really very technical and requires time to understand.  I noticed that Python seems to be the language of choice for machine learning, but I only stumbled upon a few.  Have to dig in some more.
  • There is also Microsoft Azure Machine Learning which would be interesting to check too.

Quick refresher on JavaScript’s objects, prototypes and inheritance


Here is how we commonly code JavaScript’s objects, prototypes and inheritance.  You can copy the JavaScript code below and quickly run it on any online JavaScript compiler/runner app on the Internet.  I use JS Bin.

// If we don't need to create/instantiate objects, then an object literal will do
console.log("*****Object Literal*****");
var EmployeeMe = {
  FullName: "Rodan Sotto",
  HireDate: "12/1/2015",
  Save: function(){
    console.log("Employee saved: " + this.FullName + ", " + this.HireDate.toString());
  }
}

EmployeeMe.Save(); // displays "Employee saved: Rodan Sotto, 12/1/2015"

console.log(EmployeeMe); // displays the object literal itself
console.log(Object.getPrototypeOf(EmployeeMe)); // displays the object literal's prototype which is Object


// Otherwise, we would use a constructor function to define the properties of the class
console.log("*****Constructor Function*****");
var Employee = function(fullName, hireDate){
  this.FullName = fullName;
  this.HireDate = hireDate;
}

// ... and on the constructor's prototype property to define the methods of the class
// We actually can define the methods inside the constructor but it's common practice
//  to define them on the prototype to get the maximum benefit of the prototypal inheritance
Employee.prototype.Save = function(){
    console.log("Employee saved: " + this.FullName + ", " + this.HireDate.toString());  
}

var e = new Employee("Rodan Sotto", "12/1/2015");
e.Save(); // displays "Employee saved: Rodan Sotto, 12/1/2015"

console.log(Employee); // displays the Employee constructor
console.log(Employee.prototype); // displays an object containing the Save() method
console.log(Employee.prototype.constructor); // displays the original constructor (e.g. the Employee constructor)
console.log(Object.getPrototypeOf(e)); // displays the Employee prototype
console.log(Object.getPrototypeOf(Object.getPrototypeOf(e))); // displays Object


// To inherit from Employee, the following is the common pattern used
// Notice the call to Employee.call(), this calls the Employee constructor but runs it in the context of the Manager by passing "this"
console.log("*****Inheritance*****");
var Manager = function(fullName, hireDate, companyShares){
  Employee.call(this, fullName, hireDate);
  this.CompanyShares = companyShares;
}

// The next statement is needed to allow Manager to inherit properties and methods defined on the Employee constructor's prototype
Manager.prototype = Object.create(Employee.prototype);

// Because of the previous statement, the Manager constructor's prototype's constructor is set to the Employee constructor
//  and we do not want that, so we need to fix this to point to the Manager constructor
Manager.prototype.constructor = Manager;

var m = new Manager("John Smith", "1/1/2000", 1000);
m.Save();
console.log(Manager); // displays the Manager constructor
console.log(Manager.prototype); // displays an object containing the constructor property and the inherited Save() method
console.log(Manager.prototype.constructor); // displays the Manager constructor
console.log(Object.getPrototypeOf(m)); // displays the Manager prototype
console.log(Object.getPrototypeOf(Object.getPrototypeOf(m))); // displays Employee prototype
console.log(Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(m)))); // displays Object

// As we can see in the last three statements how Manager inherits Employee
//  and the Employee inherits from Object by traversing the prototype chain

TypeScript Notes: Part 2


Part 2 is all about classes, interfaces, abstract classes, and inheritance in TypeScript.  It’s similar to OOP in C#.  So easy to grasp and use that one might totally forget how OOP in JavaScript works.  Same as in TypeScript Notes: Part 1, I will present the TypeScript code and the generated JavaScript code.  The generated JavaScript code might be overwhelming to understand at first but as long as your knowledge with JavaScript objects is still intact, you should be able to figure it out.  For a refresher, read MDN’s Introducing JavaScript objects.

// TypeScript Notes: Part 2


// Classes, access modifiers, properties, constructor
class Employee {
    FullName: string;
    public HireDate: Date; // this is a Javascript Date object
    private Salary: number;
    protected HomeAddress: string;

    // properties / accessors
    private _position: string;
    get Position(): string {
        return this._position;
    }
    set Position(position: string) {
        this._position = position;
    }

    // constructor
    constructor() {
        console.log("Employee object created");
    }

    Save(): void {
        console.log("Employee saved: " + this.FullName + ", " + this.HireDate.toLocaleDateString());
    }
}

let e: Employee = new Employee(); // displays "Employee object created"
e.FullName = "Rodan Sotto";
e.HireDate = new Date("12/1/2015");
e.Save(); // displays "Employee saved: Rodan Sotto, 12/1/2015"

e.Salary = 0; // compile-time error because e.Salary is declared private; default access modifier is public
console.log("Salary set to " + e.Salary);

e.HomeAddress = "Mississauga, ON"; // compile-time error because e.HomeAddress is protected
console.log("Home address set to " + e.HomeAddress);

e.Position = "Senior Software Developer";
console.log("Position set to " + e.Position); // displays "Position set to Senior Software Developer"
// Note: To support properties / accessors, at minimum, ES5 is required


// Using shorthand properties to initialize properties at construction
class Employer {
    // specifying access modifier before constructor parameter makes it a property
    // in the example below, Name and Address are properties while misc is not
    constructor(public Name: string, public Address: string, misc: string) {
    }
}



let er: Employer = new Employer("Acme Company", "Ontario, Canada", "xyz");
console.log("Employer: " + er.Name + ", " + er.Address); // displays "Employer: Acme Company, Ontario, Canada"


// Inheritance, protected variables in derived classes
class Manager extends Employee {
    constructor(public CompanyShares: number, address: string) {
        super(); // required call for derived classes
        this.HomeAddress = address; // protected variable is accessible to derived classes
    }

    // method to return the protected variable HomeAddress
    GetHomeAddress(): string {
        return this.HomeAddress;
    }
}






let m: Manager = new Manager(1000, "Toronto, ON"); // displays "Employee object created"
m.FullName = "John Smith";
m.HireDate = new Date("1/1/2000");
m.Position = "Development Manager";
m.Save(); // displays "Employee saved: John Smith, 1/1/2000"
console.log("Company shares set to " + m.CompanyShares); // displays "Company shares set to 1000"
console.log("Home address set to " + m.GetHomeAddress()); // displays "Home address set to Toronto, ON"


// Template strings
// To use, enclose your template string with the tick symbol (`)
//  and enclose the variables in ${} notation
console.log(`Manager ${m.FullName} is hired ${m.HireDate.toLocaleDateString()} as a ${m.Position} and he lives in ${m.GetHomeAddress()}`);
// displays "Manager John Smith is hired ?1?/?1?/?2000 as a Development Manager and he lives in Toronto, ON"


// Interfaces
interface ICanSing {
    Sing(): void;
}

interface ICanDance {
    Dance(): void;
}

class Person implements ICanSing, ICanDance {
    constructor(public Name: string) {
    }

    Sing(): void {
        console.log(`${this.Name} can sing!`);
    }

    Dance(): void {
        console.log(`${this.Name} can dance!`);
    }
}




let j: Person = new Person("Jane");
j.Sing(); // displays "Jane can sing!"
j.Dance(); // displays "Jane can dance!"


// Abstract classes
// In an abstract class you can have partial implementation while in an interface you cannot
// Plus you cannot extend more than one abstract class while you can implement more than one interface
abstract class AbstractPerson {
    ShowAbilities(): void {
        if (this.CanSing) this.Sing();
        if (this.CanDance) this.Dance();
    }

    CanSing: boolean;
    CanDance: boolean;
    abstract Sing(): void;
    abstract Dance(): void;
}



class AnotherPerson extends AbstractPerson {
    constructor(public Name: string) {
        super();
    }

    Sing(): void {
        console.log(`${this.Name} can sing!`);
    }

    Dance(): void {
        console.log(`${this.Name} can dance!`);
    }
}







let k = new AnotherPerson("Kane");
k.CanSing = true;
k.CanDance = false;
k.ShowAbilities();

// Generated JavaScript Code From TypeScript Notes: Part 2


// Classes, access modifiers, properties, constructor
var Employee = /** @class */ (function () {
    // constructor
    function Employee() {
        console.log("Employee object created");
    }
    
	Object.defineProperty(Employee.prototype, "Position", {
        get: function () {
            return this._position;
        },
        set: function (position) {
            this._position = position;
        },
        enumerable: true,
        configurable: true
    });
    
	Employee.prototype.Save = function () {
        console.log("Employee saved: " + this.FullName + ", " + this.HireDate.toLocaleDateString());
    };
    
	return Employee;
}());


var e = new Employee(); // displays "Employee object created"
e.FullName = "Rodan Sotto";
e.HireDate = new Date("12/1/2015");
e.Save(); // displays "Employee saved: Rodan Sotto, 12/1/2015"

e.Salary = 0;
console.log("Salary set to " + e.Salary);

e.HomeAddress = "Mississauga, ON";
console.log("Home address set to " + e.HomeAddress);

e.Position = "Senior Software Developer";
console.log("Position set to " + e.Position); // displays "Position set to Senior Software Developer"



// Using shorthand properties to initialize properties at construction
var Employer = /** @class */ (function () {
    function Employer(Name, Address, misc) {
        this.Name = Name;
        this.Address = Address;
    }
    
	return Employer;
}());

var er = new Employer("Acme Company", "Ontario, Canada", "xyz");
console.log("Employer: " + er.Name + ", " + er.Address); // displays "Employer: Acme Company, Ontario, Canada"


// Inheritance, protected variables in derived classes
var Manager = /** @class */ (function (_super) {
    __extends(Manager, _super);
    
	function Manager(CompanyShares, address) {
        var _this = _super.call(this) || this;
        _this.CompanyShares = CompanyShares;
        _this.HomeAddress = address;
        return _this;
    }
    
    Manager.prototype.GetHomeAddress = function () {
        return this.HomeAddress;
    };
    
	return Manager;
}(Employee));

var m = new Manager(1000, "Toronto, ON"); // displays "Employee object created"
m.FullName = "John Smith";
m.HireDate = new Date("1/1/2000");
m.Position = "Development Manager";
m.Save(); // displays "Employee saved: John Smith, 1/1/2000"
console.log("Company shares set to " + m.CompanyShares); // displays "Company shares set to 1000"
console.log("Home address set to " + m.GetHomeAddress()); // displays "Home address set to Toronto, ON"


// Template strings


console.log("Manager " + m.FullName + " is hired " + m.HireDate.toLocaleDateString() + " as a " + m.Position + " and he lives in " + m.GetHomeAddress());



// Interfaces








var Person = /** @class */ (function () {
    function Person(Name) {
        this.Name = Name;
    }
    
	Person.prototype.Sing = function () {
        console.log(this.Name + " can sing!");
    };
    
	Person.prototype.Dance = function () {
        console.log(this.Name + " can dance!");
    };
    
	return Person;
}());

var j = new Person("Jane");
j.Sing(); // displays "Jane can sing!"
j.Dance(); // displays "Jane can dance!"


// Abstract classes


var AbstractPerson = /** @class */ (function () {
    function AbstractPerson() {
    }

    AbstractPerson.prototype.ShowAbilities = function () {
        if (this.CanSing)
            this.Sing();
        if (this.CanDance)
            this.Dance();
    };

    return AbstractPerson;
}());

var AnotherPerson = /** @class */ (function (_super) {
    __extends(AnotherPerson, _super);
    
	function AnotherPerson(Name) {
        var _this = _super.call(this) || this;
        _this.Name = Name;
        return _this;
    }
    
	AnotherPerson.prototype.Sing = function () {
        console.log(this.Name + " can sing!");
    };
    
	AnotherPerson.prototype.Dance = function () {
        console.log(this.Name + " can dance!");
    };
    
	return AnotherPerson;
}(AbstractPerson));

var k = new AnotherPerson("Kane");
k.CanSing = true;
k.CanDance = false;
k.ShowAbilities();


// This is the __extends code used to implement classes extending another class or abstract class in Typescript
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    
	return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

SQL Tricks: CSV To Table Rows And Vice Versa


I was looking for a one-line SQL statement to convert a comma-separated value list string to table rows and vice-versa and below is what I found.  I prefer not to put logic in my SQL code (I prefer to limit it with just the simple CRUD statements) but if no other choice then these two SQL tricks will come in handy.  You can try to execute this SQL query on any online SQL compiler you can find on the Internet, but I would recommend rextester’s sql compiler.

-- So if you have a comma separated list, for example a list of integers
DECLARE @MyListOfInts VARCHAR(255) = '123,456,789'

-- Use the following SQL trick to parse them to table rows
-- Basically you convert the CSV to XML first and use the nodes() method to shred the XML into relational data
SELECT List.Item.value('.', 'INT')
FROM
(
    SELECT CAST('<List><Item>' + REPLACE(@MyListOfInts,',','</Item><Item>') + '</Item></List>' AS XML) AS ListXML
) ListXMLTable
CROSS APPLY ListXMLTable.ListXML.nodes('/List/Item') List(Item)


-- And if you have values in table rows that you want to convert to CSV...
-- The following SQL trick will do it for you
-- Basically the inner SELECT query with unnamed column and with FOR XML PATH('') converts the 
--  table row values to XML without any tags and the SUBSTRING() function in the outer SELECT query
--  just removes the leading comma character
SELECT SUBSTRING
(
    (
        SELECT ',' + CAST(List.Item AS VARCHAR(MAX))
        FROM
        (
            SELECT 123 AS Item UNION SELECT 456 UNION SELECT 789
        ) List
        ORDER BY List.Item
        FOR XML PATH('')
    )
    ,2
    ,1000
)