Category Archives: Languages

TypeScript and AngularJS part 2; the Good, the Bad and the Ugly.

As will become clear, this is the takehome message:

  • Directives and Factories, because they are used without new(), must be created as static TypeScript objects.
  • Controllers and Services can be plain old typescript objects (potsos?)

Naturally, there are ramifications.

Let’s start at the end, where everything is combined and delivered to Angular:

module AngularApp {
   // define how this application assembles.
   class AngularMain {
      serviceModule:ng.IModule;
      appModule:ng.IModule;

      public doCreate(angular:ng.IAngularStatic, tcontroller:Function, tservice:Function, tfactory:Function, tdirective:Function) {
         this.serviceModule = angular.module('globalsApp', [])
            .factory('GlobalsFactory', [tfactory])
            .service('GlobalsService', [tservice]);

         this.appModule = angular.module('simpleApp', ['globalsApp'])
            .controller('MainCtrl', ['GlobalsFactory', 'GlobalsService', tcontroller])
            .directive('testWidget', ['GlobalsService', tdirective]);
      }
   }
   // instantiate Angular with the components defined above.
   new AngularMain().doCreate(angular, InheritApp.TestController2, InheritApp.TestService, InheritApp.TestFactory.ctor, InheritApp.TestDirective2.ctor);
}

This structure isn’t needed, but as with the last post, I kind of like the way it looks. The first thing to notice is that the angular-specific code is wrapped in its own module and class within that module. Since this isn’t going to get called outside of the module (this would be custom for each application), I didn’t bother with an interface. Once the class is built, I call it with the arguments that will be used by Angular to build the application. There are two things to note: the arguments with the ctor member are static. The items with a ‘2’ in their names are child classes, built with typescript-defined inheritance.

Let’s take a look at the controller and the service that gets passed in.

Controllers and Services, since they are instances, require virtually no contortions to use. A controller is declared pretty much just the way you’d want to. (I have the classes for this example wrapped in a module that I can then export from – full code here) . The following controller has an interface, a class that implements that interface, and a constructor that takes angular injections.

export interface ITestController {
   myString:string;
   serviceString:string;
   factoryString:string;
}
export class TestController implements ITestController {
   myString:string;
   serviceString:string;
   factoryString:string;

   constructor(gFactory:ITestService, gService:ITestService) {
      this.myString = "Hello, TypeScript4";
      this.serviceString = gService.getHello();
      this.factoryString = gFactory.getHello();
   }
}

The child class is built as follows. I added a new variable, and modified a parent variable in the constructor::

// example on an inherited interface and controller
export interface ITestController2 extends ITestController {
   myInheritedString: string;
}
// the associated controller.
export class TestController2 extends TestController implements ITestController2 {
   myInheritedString:string;

   constructor(gFactory:ITestService, gService:ITestService) {
      super(gFactory, gService);
      this.myInheritedString = "Hello, inheritance";
      this.myString += " from your child"
   }
}

In case you were wondering (you can look at the generated code here), typescript uses parasitic inheritance.

The service in this example is constructed essentially identically to the controller:

// example service with interface
export interface ITestService {
   helloStr:string;
   getHello():string;
}
export class TestService implements ITestService {
   helloStr:string;

   constructor() {
      this.helloStr = "TestService String";
   }

   public getHello():string {
      return "Hello from TestService";
   }
}

Now let’s compare the service to a factory. Factories are set up by angular to be singletons, while services can breed like bacteria and clog all your memory. Typescript uses a static** property to define singletons, so a factory in typescript looks like this:

// Factory. Like the directive, factories are called without new, 
// so no this, and all references to the factory are references 
// to the same object. 
export class TestFactory {
   static helloStr:string = "TestFactory String";

   public static ctor() {
      var retval = {
         getHello: TestFactory.getHello
      };
      return retval;
   }

   public static getHello():string {
      return TestFactory.helloStr;
   }
}

This is a little more clunky, but it does make what’s going on clearer, at least for me. Note how you can’t have any items attached to the ‘this’ object. They have to be explicitly attached to the ‘class definition’. As such the static/singleton status is hard to overlook.

Inheritance will work on static classes, but with some odd considerations. This is the parent and child directives:

// directives have to be static, as they are called without the 
// 'new' operator, which means they have no 'this' They also 
// don't get interfaces, since all the functions are static 

export class TestDirective implements ng.IDirective {

   public static  linkFn(scope:any, element:any, attr:ng.IAttributes) {
      function sayIt(str:string):string{
         return str;
      }
      scope.name = "Hello from linkFn";
      scope.sayIt = sayIt;
      alert (sayIt("alert me!"));
   }

   public static ctor(gService:ITestService):ng.IDirective {

      var directive:ng.IDirective = {};
      directive.template = '<p>Directive (Ctor) = ' + gService.getHello() + ', linkFn = {{name}}</p>';
      directive.restrict = 'AE';
      directive.link = TestDirective.linkFn; // silly, but necessary.
      return directive;
   }
}

export class TestDirective2 extends TestDirective {
   public static ctor(gService:ITestService):ng.IDirective {

      var directive:ng.IDirective = {};
      directive.template = '<p>Inherited Directive (Ctor) = ' + gService.getHello() + ', linkFn = {{name}}</p>';
      directive.restrict = 'AE';
      directive.link = TestDirective2.linkFn; // silly, but necessary.
      return directive;
   }
}

There are a couple of things to note in the code above. First, the directive as it is built in the ctor() method is created as an empty object and then populated. This is how I found it being done in examples on the web, and I believe it helps determine typing. I’m not convinced though – I’ll have to check by putting something mis-typed inside the object definition. By the way, note that services or factories can be passed to the directive as arguments to the ctor() method.

The second odd thing is the directive.link function. I would have thought that this could have been done a variety of ways, but this is how Angular likes it. And because everything is static, I wound up using functions inside the linkFn class since you can’t nest typescript-style methods in a clear way.

With respect to inheritance, directives are going to be a pain.  You can’t easily overload parts of the parent class to add capability to the child class. It may actually be easier to use inheritance on just the link function. I’m still not sure what the best way to go on that is. It will probably only become clear when I try to write some sophisticated directives (and, boy do I have one to work on…).

So there is good, not-so-bad and ugly. I’d be curious if anyone has a better pattern, particularly for directives.

—————————-

** It turns out that there is a non-static way to treat directives and factories, which is instancing them and then passing a function reference to angular. I think this works much better. For more detail, check out this post.

OOooo… TypeScript Classes with AngularJS

Let’s add TypeScript to the mix. I like typing – basically because I hate making unforced errors. I like interfaces for the same reason – they allow defining complex types before they get used.

I’ve known about TypeScript for a while, but I wasn’t good enough with JavaScript to really understand what it was doing. It just didn’t seem like a good idea to add yet another abstraction to the already shaky tower of JavaScript, Angular and threeJS.

But now I’ve been working with some reasonably complex JavaScript and have enough comprehension to understand the conversions that TypeScript makes. I might even be consciously competent:

TypeScript has been used with Angular before, and it’s also part of the plan for Angular 2.0. Sean Hess has a nice angular with typescript video. The key points are really around 15:00 in, where the controllers and factories are built. His github repository for the demo code is here. It was great to see that TypeScript and Angular can be combined, but I really wanted something as simple as possible, so I got a copy of TypeScript Essentials and started with the basics.

With that in mind, I’ve tried to make a very simple TypeScript class and incorporate it into the angular framework using a second TypeScript class. In the interest of maximum simplicity, there are only classes and typing – no interfaces (other than the ones from definitely typed) and no modules. No inheritance either. All these will be in a later post.

So, without any more introduction, here are the results:

  • First, plain old angular HTML:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body ng-app="simpleApp">
<div ng-controller="MainCtrl as mc">
    <p>String = {{mc.myString}}</p>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="simple.js"></script>

</body>
</html>
  • Next, the TypeScript (simple.ts):
/// <reference path="../definitelytyped/angularjs/angular.d.ts" />

class TestClass{
   myString:string;

   constructor(){
      this.myString = "Hello, TypeScript4";
   }
}

class AngularMain{
   myModule:ng.IModule;
   myController:ng.IModule;
   public doCreate(angular:ng.IAngularStatic, sfn:Function){
      this.myModule = angular.module('simpleApp', []);
      this.myController = this.myModule.controller('MainCtrl', [sfn]);
   }
}

new AngularMain().doCreate(angular, TestClass);
  • Last, the generated JavaScript code (simple.js):
/// <reference path="../definitelytyped/angularjs/angular.d.ts" />
var TestClass = (function () {
    function TestClass() {
        this.myString = "Hello, TypeScript4";
    }
    return TestClass;
})();
var AngularMain = (function () {
    function AngularMain() {
    }
    AngularMain.prototype.doCreate = function (angular, sfn) {
        this.myModule = angular.module('simpleApp', []);
        this.myController = this.myModule.controller('MainCtrl', [sfn]);
    };
    return AngularMain;
})();
new AngularMain().doCreate(angular, TestClass);
//# sourceMappingURL=simple.js.map

I’ve put a running example up here.

Happy coding!

OO inheritance for AngularJS factories

AngularJS  services and factories require a return object. As such, the parasitic combination inheritance calls mentioned in the previous post need to be changed a bit so that the return object from the call to the parent class is stored so that it can be returned from the child class in a way that Angular likes. Here’s what it looks like when using my ‘utility’ inheritance tools:

function QueryServiceFn2($http){
   var retObj = QueryServiceFn.call(this, $http);
   globalU.inheritPrototype(this, QueryServiceFn);
   return retObj;
}

So that works just fine. Closure also works the way that I think it should – methods referenced in the parent class have visibility to the ‘hidden’ parent objects. Here’s full example of inheriting a factory object (full version here – the child class is at the bottom of the file):

globalUtils.appMap.phpFactories2 = (function(globalU, base){
   "use strict";
   function QueryServiceFn($http){
      var retObj = base.call(this, $http);
      globalU.inheritPrototype(this, base);
      return retObj;
   }

   return{
      queryServicePtr: QueryServiceFn
   };
})(globalUtils, globalUtils.appMap.phpFactories.queryServicePtr);

To override a function, simply declare it normally and then set the pointer in retObj to point at the new version. The only thing to watch out for is that closure won’t hold. If you need access to an item in the base class that’s accessed through closure, you’ll probably have to copy it.

OOPs! Inheritance for AngularJS redux…

So it turned out that what I thought was parasitic combination inheritance was just parasitic. The globalUtils.inheritPrototype() function was being called before the function/objects were being called, thus inheriting nothing.. I think that this is because Angular is calling the functions after the other JavaScript is called. Since (I think!) the code has to be structured in this decoupled way to allow flexible use of OO, I had to look again at how all the pieces fit together. It turns out that a properly configured function object that inherits from a base class looks like this:

function ChildFn3(globalService) {
    console.log("Start ChildFn3");
    ChildFn2.call(this, globalService);
    globalU.inheritPrototype(this, ChildFn2);
    console.log("Finish ChildFn3");
}

we can adjust inherited values such as arrays without ‘static’ behaviors as well:

function ChildFn4(globalService) {
    console.log("Start ChildFn4");
    ChildFn2.call(this, globalService);
    globalU.inheritPrototype(this, ChildFn2);
    this.colors.push('black');
    console.log("Finish ChildFn4");
}

Here’s the better, running example: http://philfeldman.com/inheritance/inherit3.html

OOP Inheritance for AngularJS

First, the caveat – I’ve just gotten this example to work. I will try using it in some larger code shortly, but I thought I’d document while everything seemed clear.

I’ve been working with Angular for a few months now, and am now doing reasonably complex things. As someone who has been coding for way too long, I like some of the things that Object Oriented programming gives you that Angular does not support (at least in a straightforward way). Primary among this is inheritance. I ran into this problem when I needed to make two mostly similar web pages that really didn’t lend themselves to multiple services/factories but could have been very cleanly built by extending a base class.

In Java/C++/Actionscript, etc, you have the capability to build base classes that can be extended. An example is setting up a particle base class that is extended to a moving particle class inherits from (Using Java here):

public class Particle{
    private vec3 position;
    public function setPosition(vec3 p){
        // code...
    }
    public function draw(){
        // code...
   }
}

To make the particle move, we need to add some kind of velocity and an update function that increments the position as a function of the velocity and time.

public class MovingParticle extends Particle{
    private vec3 velocity;
    public function setVelocity(vec3 p){
        // code...
    }
    public function update(double elapsed){
        // code...
   }
}

JavaScript has nothing like this and neither does Angular. YUI did, but that’s not supported any more. But through some contortions, JavaScript can handle inheritance. A pattern that I like is Parasitic Combination Inheritance, which I learned about in Professional JavaScript for Web Developers. I combined that with the Revealing Module Pattern, to get inheritance to work in a clean way. A fully working version of the code below is up at plunker. Some sections of the code below have been stripped out for clarity.

First, the base class:

var baseLogic = (function(window, undefined) {
    function ParentFn(globalsService) {
        this.myText = "Hello, World";
        this.myText2 = globalsService.getHello();
    }

    ParentFn.prototype.makeAlert = function() {
        alert(this.myText2);
    };

    return {
        parentPtr: ParentFn
    }
})(window);

Note that the baseLogic object is a function expression where the only accessible attribute is parentPtr, which points to the hidden function declaration ParentFn.

The child class uses a similar pattern. I pass in the baseLogic object just to keep things cleaner. Additionally, I pass in a globals object (created just like baseLogic) that contains a function that handles the mechanics of Parasitic Combination Inheritance.

var myLogic = (function(window, base, gbl, undefined) {
    //function ChildFn(){
    function ChildFn(globalsService) {
        var self = this;
        base.parentPtr.call(self, globalsService);
        self.myText = "Hello, World2";
        self.instanceAlert = function() {
            alert("instanceAlert = " + self.myText);
        }
    }

    gbl.inheritPrototype(ChildFn, base.parentPtr);

    ChildFn.prototype.makeAlert2 = function() {
        alert("ChildFn.prototype.makeAlert2");
    };

    return {
        childPtr: ChildFn,
    }

})(window, baseLogic, globals);

These can then be incorporated in Angular pretty trivially. The globalsService that is an argument in both the parent and child objects is created in the same way:

(function(angular, ml, undefined) {
    angular.module('globalsApp', [])
            .factory('GlobalsService', [ml.factoryPtr]);

    angular.module('inheritApp', ['globalsApp'])
            .controller('MainCtrl', ['GlobalsService', ml.childPtr]);
})(angular, myLogic);

The nice thing about this approach is that any component (controller, link functions in directives, factory, service) can all be built using OO techniques this way.

Here’s hoping it works on something more than my toy example

So here we are, several days later. Everything works like I hoped. Now all the angular code for a module is in one place, which looks nice and readable (example). And although it’s kind of messy (programming for school, rather than work), here’s the base class and the derived class that is used in the

.controller('MainCtrl', ['$http', '$timeout', '$document', 'PostService', postControllers.turkPostPtr])

call in the above example.

Woohoo!

Trigraphs and digraphs and milliseconds oh my!

I’ve been reading my papers on recognizing biometrics from keystroke info and it generally seems to either work from training neural nets or from examining the timing of certain letter patterns, particularly digraphs and trigraphs. I’m currently working on parsing the raw data into more manageable data that can be stored in a form specific table:

CREATE TABLE IF NOT EXISTS `trigraph_table` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `session_id` varchar(255) NOT NULL,
  `word` varchar(255) NOT NULL,
  `milliseconds` int(11) NOT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

I can point back to the session_table for all the associated data if there is not sufficient clustering with just the session_id. Speaking of the session_table, it’s getting downright scary:

CREATE TABLE IF NOT EXISTS `session_table` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`session_id` varchar(255) NOT NULL,
`type` int(11) NOT NULL,
`entry_time` datetime NOT NULL,
`ip_address` varchar(255) NOT NULL,
`browser` varchar(255) NOT NULL,
`referrer` varchar(255) NOT NULL,
`submitted_text` text NOT NULL,
`raw` MEDIUMTEXT NOT NULL,
`parent_session_id` varchar(255) DEFAULT NULL,
`veracity` int(11) NOT NULL,
`hostname` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`region` varchar(255) NOT NULL,
`country` varchar(255) NOT NULL,
`latlong` varchar(255) NOT NULL,
`service_provider` varchar(255) NOT NULL,
`postal` varchar(255) NOT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

The idea that we are anonymous is just silly, from the moment we connect to a server, we’re basically exposed. And I’m just getting started with gathering data. Imagine what experienced web developers can do, particularly once cookies are enabled. Minimising that damage to someone who posts to the site is probably on the list of things to look at. Maybe server hardening? Certainly no links from the page.

On a different note, I’ve been thinking a bit about how confident we need to be of a source before we can start determining information trustworthiness. It seems to me that if we can show that the information comes from a wide number of individuals, we get information as well, even if we can’t sufficiently distinguish one. That trips up the one individual reporting something unique scoop aspect though.

Another thing that’s kind of interesting is typos and spell check. Keeping track of typos is easy – just run everything through a dictionary. A different, also potentially useful thing is to look at the differences in words produced by keystrokes and the submitted text. Where those differ, some sort of spell correction was used, which doesn’t behave like a paste, or it would be trapped. Anyway, it’s another form of interesting data.

 

Plans coming together

Ok, things are getting close. I have all the code pieces talking in a single application (http://philfeldman.com/irev1.html). After playing around with the ways that the key down/up events can be trapped, I decided to do as little processing as possible and simply record the keycode, time and status (up/down). The main reason for this is that things like the shift key are pressed while other keys are typed and then released. This way it’s easier to see that happen.

I also needed to prevent pasting, since that makes everything more complex (recognizing paste events, working around them, etc). It turns out that YUI dosn’t seem to handle the paste event, so you have to get it from the document directly:

var pasteTrap = document.getElementById('submittedTextInput');
pasteTrap.onpaste = function(e){
    alert("Paste is not allowed");
    return false;
}

As usual, we have the fine contributors to StackOverflow to point the way to do this

Amazingly, it even works in all browsers.

Next is cleanup, putting all the pieces into modules where they belong and doing some better css. I think something like secret might be pretty easy to put together. Colored backgrounds before coding up picture loading. But along those lines.

Last thing for the day is to finish the next pass at the IRB submission.

Safe(er) Data and Nonexistent Functions

If you want to reduce the likelihood of a SQL injection attack, use, precompiled queries. Nice in theory, tougher in practice. The nub of the problem appears to be the way that PHP binds data to execute the insert or the pull. With a nice, vulnerable query you can use string manipulation functions and as such make nice, general functions. However, if you’re mean, you can add something like “;DROP TABLE students; and poof, the table students is gone. Now, there should be a nice call that returns everything as an associative array, but that doesn’t seem to be reliable across PHP installations, so we need to work with the much more restrictive fetch();

Things to remember:

  • Everything has to happen when the statement is available, between prepare() and close().
  • Use bind_params(String datatypes…) to send data and bind_results for returning data. bind_params is less picky – you can access elements of an array directly. For bind_results you have to have individual variables declared.
  • When things go wrong in the PHP mysql code, it is likely that an HTML table will be returned. That will need to be handled.
  • Stringify and parse of objects into and out of JSON may or may not handle hierarchies. Watch what goes on in the debugger.

Anyway that just about doubled the line count in the middleware and bound the PHP code much more tightly to the form of the database. That being said, this is intended to have some production values in it anyway, so that may be a good thing. The new and improved results are in the same old place, namely io2.html. Next comes the integration of all that DB work, the recognizer part, and the panel part.

Basic Chores

Not much to write about, but some good work got squeezed in today. First, I was able to transition over to mysqli, which turned out to be nearly painless. I’ve been working on a thin layer that’s admittedly got some security holes, but that’s not what I’m trying to work through and the data’s junk anyway.

So to get use out of all this stuff, I need to have everything run on a server. I use Dreamhost, who I like a lot and have been with for years, and they give you PHP and mysql out of the box. So today was the day to try and take all the pieces that I have gotten working on my dev machine and migrate them to a place that people can access.  It did mean getting familiar with SSH and PuTTY all over again though.

The first step was creating a database. Since I’m on a shared server, that’s not as simple as when you own the instance, but Dreamhost has a dashboard that makes this pretty reasonable. It does take time though for everything to trickle through though. Once it was up and running I created a new copy of the same old table I’ve been using for my tests and populated it with the same old data.

Once that was done I fired up WinSCP and copied the files over, changed the config file and tried running the php script on the command line. Imagine my surprise when everything ran right the first time. And then compound that again when the web page worked as well. And both of those files had no changes. Repeat after me:

“Configuration files are wonderful”

“Relative addressing is also”

Anyway, here it is in all its glory: io2.html.

The next part is handling the submission of data to the db, which is making me a bit nervous about sql injection. I may just use the YUI Escape object to modify the string so it isn’t dangerous. Nope, that won’t work, but we can use blobs. Here’s how (from here):

/**
 * update the files table with the new blob from the file specified
 * by the filepath
 * @param int $id
 * @param string $filePath
 * @param string $mime
 * @return boolean
 */
function updateBlob($id,$filePath,$mime) {
$blob = fopen($filePath,'rb');

$sql = "UPDATE files
SET mime = :mime,
data = :data
WHERE id = :id";

$stmt = $this->conn->prepare($sql);

$stmt->bindParam(':mime',$mime);
$stmt->bindParam(':data',$blob,PDO::PARAM_LOB);
$stmt->bindParam(':id',$id);

return $stmt->execute();

}

On a related note, I wonder how many of our actions can be stereotyped in a way that can be detected in the browser?