Spies and secret agents in javascript

Hello everybody,

Have you ever had a desire to become chief of secreat agent or spy? To be honest I never had such desire, but unwilignly I become chief of spies  and secret agents which I created in javascript. 

To put simply during unit testing of javascript sometime is needed to mock calling to some functions with replacement of that function, and sometime there is a need to mock that function without it's replacement. 

The first scenario is much easier to implement, while the second one required usage of apply function. 

Take a look at the following picture:

There are many js libraries which support both options ( with and without original function ). For example jasmine, sinonjs, etc. But I want to present code which display simple idea what is going behind the curtains.

 

<html>
 <head></head>
 <body>
   This content doesn't matter  
  <script>
		
		var ClassForSpy = function(){
		};
		
		ClassForSpy.prototype.Function1 = function(){
			console.log('Function1 executed');
			return true;
		};
		
		var InheritedClass = function(){};
		
		InheritedClass.prototype = new ClassForSpy();
		
		InheritedClass.prototype.Function2 = function(){
			console.log('Function1 inside inherited class');
			return 'Anything';
		};
		
		function CoolSpy(victim){
			for(var key in victim)
			{
				victim[key] = CreateCoolSpy(key);
			}
		}
		
		function CoolSecretAgent(victim){
			for(var key in victim)
			{
				victim[key] = CreateSecretAgent(key, victim, victim[key]);
			}
		}
		
		function CreateCoolSpy(key){
			return function(){
				console.log('CoolSpy for ' + key);
			}
		};
		
		function CreateSecretAgent(key, context, originalFunction){
			var sendToCenter = function()
			{
				console.log('I have send to command center secret info ' + key );
				return originalFunction.apply(context, arguments);
			};
			return sendToCenter;
		}
		
		console.log('Before spy section started')
		var inhClass = new InheritedClass();
		inhClass.Function1();
		inhClass.Function2();
		console.log('--------------------Before spy section completed-------------------');
		
		
		console.log('diletant spy or spy that substitutes original Function executed');
		CoolSpy(inhClass);
		
		inhClass.Function1();
		inhClass.Function2();
		console.log('substitutes spy section ended');
		
		console.log('Invisible spy section started');
		var inhClass2 = new InheritedClass();
		CoolSecretAgent(inhClass2);
		inhClass2.Function1();
		inhClass2.Function2();
		
		console.log('Invisible spy section ended');
		
	</script> 
 </body>
</html>

 

If you copy/paste the following code, and look in console, you'll find following output there:

Before spy section started

Function1 executed

Function1 inside inherited class

--------------------Before spy section completed-------------------

diletant spy or spy that substitutes original Function executed

CoolSpy for Function1

CoolSpy for Function2

substitutes spy section ended

Invisible spy section started

I have send to command center secret info Function1

Function1 executed

I have send to command center secret info Function2

Function1 inside inherited class

Invisible spy section ended

Here we have two functions which imitate spies behaviour. The first one is CoolSpy  and second one is CoolSecretAgent .

CoolSpy is interesting for cases if it is needed to substitute behaviour of some code, CoolSecretAgent can be used for monitoring of execution.

AngularJS ng-options

Hello everybody,

today I want to make some post about how to work with AngularJS select directive from viewpoint of complicated objects. 

<select id="type"

              class="form-control" name="type" aria-readonly="true"

               ng-model="course.courseId">

                 <option ng-selected="{{ course.courseId== et.id }}"

                   ng-repeat="et in courseTypes" value="{{et.id}}">{{et.name}}

                 </option>

</select>

 

In controller I have some code which populates data from controller for course types, and in order to display complicated parts I applied mentioned before select.

What the difference between programmer and software developer?

Hello everybody,

today just short glimpse about difference between programmer and software developer.

So, try to picture following scenario, you ask for program.

As result programmer will give you a code. 

But Software developer will give you "some questions" ( and this list is not complete )

  1. How does it fit in the business process. Are the requirements thought out?
  2. Are you sure you understand what it will cost?
  3. What kind of documentation will it need?
  4. How might it interact with other code?
  5. What platform will it run on. Are the scalability issues?
  6. How might it impact future development? How might it be enhanced in the future?
  7. Can you find/buy/reuse other software instead?

After receival your answers maybe software developer will give you code. Maybe you'll buy some program.

ZenCoding in Web Essentials

Hello everybody,

today I want to point to some useful features of ZenCoding in web essentials.

Quick reference of ZenCoding shortcuts:


    # use it for creating id
    . use it for creating a class attribute
    [ ] use it for creating a custom attribute
    > use it for creating a child element
    + use it for creating a sibling element
    ^ use it for creating climbing up
    * is element multiplication. This creates the same thing n number of times
    $ is replaced with an incremental number
    $$ is used for numbers with padding
    { } creates text in an element

So, if you decide to install in your Visual Studio Web essentials, then among options which you'll get will be ZenCoding. What does it give to you?

Consider following examples:

div#menu and press tab. Web essentials will convert div#menu into the following:

<div id="menu"></div> </body>

Cool? Yep.

Let's suppose you want something more complicated. For example you want to create inside of div span with class item. You can achieve it by typing:

div#menu>span.item

and press tab. You'll get following html result:

<div id="menu"> <span class="item"></span> </div>

Now assume you want even more complicated idea with some attribute. For this purpose you can use []. Consider following example:

div#menu>span.item[title]

<div id="menu"> <span class="item" title=""></span> </div>

And you'll be able to write anything in title.

If you not get tired here is another more deep example. Imagine you want to have menu item with five li inside of it and inside of li elements let's say you want to have links and text of each link will be "Click here 01", "Click here 02", etc.

You can do like this:

ul#menu>li.menuitem*5>a{Click here $$}

and after tab you'll see the following:

<ul id="menu"> <li class="menuitem"><a href="">Click here 01</a></li> <li class="menuitem"><a href="">Click here 02</a></li> <li class="menuitem"><a href="">Click here 03</a></li> <li class="menuitem"><a href="">Click here 04</a></li> <li class="menuitem"><a href="">Click here 05</a></li> </ul></p

Notes about AngularJS webinar

Hello everybody,

few notes about some details of AngularJS.

1. What is $scope?

$scope is something where we can store information which is needed for page. Also data for changes of which we need to track.

2. How can we react on some changes in $scope? In other words if something at page modified something in model, how can we react on it? Or in another words, how to track changes in some member? 

Imagine following scenario. Inside of your scope there is a member message like this:

$scope.message = "Your message";

You can track it like this:

 

$scope.$watch("message", function(newValue, oldValue) {

    //here you can do something

});

 

newValue as you probaly guessed is new value, oldValue as you sure is oldValue.

3. What is module?

In AngularJS you work with modules. If you want to do something, you always work with modules. Module is a set of controllers, directives, filters, services, resources.

4. What is filters?

filters is everything that permits to do some actions with data. Filters always are written after | symbol. Some examples of filters:

{{message | uppercase }} - converts message to upper case.

5. How to write your filter:

in your module declaration add .filter('nameOfYourFilter');

angular.module('app', [])

.controller('somecontroller', somecontroller) .filter('toUpper', function() { return function(value) { return //some modification of your value } });

6. How to deal with minification or bundling in AngularJS?

For example like this:

MainController.$inject = ['$scope'];

Another way is to use Jamine.

7.  How to repeat some items in list?

you can use for this purpose directive ng-repeat. Imagine you have array like this

$scope.list = [1, 2, 3, 4, 5, 6, 7, 8];

you can display it like this:

<ul>

   <li ng-repeat="value in list">{{ value }} </li>  

</ul>

Another example. Imagine you have following in your controller declaration:

$scope.list = {

    'Ukraine': 'Kyiv',

    'USA': 'Washington DC',

    'UK': 'London'

}

If you use previous template you'll see only values, and not the keys. 

<ul>

   <li ng-repeat="(key,value) in list">{{ value }}, {{ key }} </li>  

</ul>

it will give you nice list of capitals with countries separated by comma.

8. How to work with routing in AngularJS?

  1. as dependencies add ngRoute
  2. add function config with $routeProvider
  3. mapp url to html template. 

Check the following example:

angular.module('app', ['ngRoute'])

    .config(function($routeProvider) {

        //here we can describe which actions should be executed at some urls.                  $routeProvider.when('/', {

            controller: 'Cntr',

            templateUrl: 'someHtmlFile.html',

            controllerAs: 'Cntr'

        }).otherwise(

            controller: 'Cntr',

            templateUrl: 'someHtmlFile.html',

            controllerAs: 'Cntr'

        )

    })

    .controller('Cntr', Cntr)

And then in html the place where we want to insert template content we need to write attribute ng-view.

9. Is it possible to have more then one module?

yes. We can have multiple modules. For example like this:

angular.module('main', [])

    .controller('MainController', MainController);

 

angular.module('app', ['ngRoute', 'main'])

    . // etc

in the described case module app will depend not only from ngRoute but also from main module.

10. Why do I need modules?

You can split your app into different modules, and then make your app from small modules.

11. What are directives?

It's something that can help to extend html. For example ng-click is directive.  

let's say that you want write in your html code  the following:  

<div capitals-list>

</div>

and you expect that browser displayed capitals which you have in your list. You can achieve it with directives. For example like this:

function CapitalsController($scope) {

    $scope.list = {

        'Ukraine': 'Kyiv',

        'USA': 'Washington DC',

        'UK': 'London'

    }

}

angular.module('app', [])

    .controller('CapitalsController', CapitalsController)

    .directive('capitalsList', function() {

        return function() {

            //return needed html

        }

});

but what if you want without div ?

then like this:

function CapitalsController($scope) {   

$scope.list = {

        'Ukraine': 'Kyiv',

        'USA': 'Washington DC',

        'UK': 'London'

    }

}

 

angular.module('app', [])

    .controller('CapitalsController', CapitalsController)

    .directive('capitalsList', function() {

        return {

            restrict: 'EA',

            link: function() {

                //return needed html

            }

        }

    });

Now puzzle time. What is E? E means that our directive will be available as html element. What means A ? A is attribute. Also there is C, which means class name. 

Yet one more complete way:

function CapitalsController($scope) {   

$scope.list = {

        'Ukraine': 'Kyiv',

        'USA': 'Washington DC',

        'UK': 'London'

    }

}

 

 

angular.module('app', [])

    .directive('capitals', function() {

        return {

            restrict: 'EA',

            controller: CapitalsController,

            templateUrl: 'html file which knows how to parse list of countries',

            link: function() {}

        }

    });

12. How not delete existing content? 

Add in directive declaration transculde: true and in html code of template add div at the top with attribute ng-transclude

13.  How to create new scope in directive?

just write scope : {  }

14. How to get into new scope something from top scope?

scope: {

     something : "@something"

}

or

scope: {

     something : "=something"

}

15. How to sync scopes of directives automatically?

There is no way. But there is a workaround. You can create your parent directive, inside of your parent directive you can have child directives which will read values from your parent directive.

16. What kind of events available in AngularJS?

$scope.$on -  listens to generated events

$scope.$emit - events which buble to the top containers

$scope.$broadcast - events which will be bubled to all child containers. To all children, to all children of all children

$http Service and promises

Hello everybody,

today another glimpse from the AngularJS world which I can name of how to get something from server.

So, imagine that you see following code in your controller:

 

var OrderController = function($scope, $http) {

    $scope.order = $http.get("/orders/1563");

}

and now is question, what's wrong with this? Just one very important issue, $http.get returns a promise, not the response itself. So in order to make it work correctly another approach will be more correct:

var OrderController = function($scope, $http) {

    var promise = $http.get("/orders/1563");

    promise.then(function(response){

      $scope.order = response.data;

          });

}

Why second approach is better? One of the reasons because promise give you guarantee that you'll receive data and display them correctly.

AngularJS mouse directives

Just short notice of AngularJS mouse directives:

ngClick,

ngDblClick,

ngMousedown,

ngMouseEnter,

ngMouseLeave,

ngMousemove,

ngMouseover,

ngMouseup

How to define properties in javascript

Hello everybody,

here is short notice of how to define properties in javascript:

 

So, lets say you want to have class Dog, with "private" field alias and public property Alias. you can achieve it in the following way:

 

function Dog(nameOfDog) {

    var alias = nameOfDog;

    Object.defineProperty(this, "Alias", {

            get: function() {

                return alias;

            },

            set: function(value) {

                alias = value;

            }

        }

    });

}

 

Later in code you can write the following:

var rex = new Dog("Rex");

var name = rex.Name;   // name will be equal to "Rex"

Also you can set name of the dog to other name. 

 

Hierarchy for CTE in MS SQL

Hello everybdoy,

today I want to write some notes about hierarchy research in ms sql database. 

Imagine you have following structure in your table 

TableWithParentChild:

id               |           rootID   |     some additional fields

1                |            1          |      ----

2                |            1          |      ----

3                |            2          |      ----

4                |            2          |      ----

5                |            2          |      ----

 

and image that you need to get info like who is below 1. 

for this purpose following sql can be useful:

-- wrap up tree selection into tvf
create function HierarchyFunction(@parentID int)
returns table
as
return
with tree
as
(select id,  rootID from TableWithParentChild
         where id = @parentID
         union all
         select p.id, p.rootID from TableWithParentChild as P
         join tree on tree.id = P.rootID
         and P.id != P.rootID
)
select * from tree

select p.* from  TableWithParentChild as p
join HierarchyFunction(1) as tree
on p.id = tree.id