Wednesday, October 29, 2014

Angular BlockUI


//Angular BlockUI 0.11
var xxxxxxModule = angular.module("xxxxxxModule", ['ngRoute', 'blockUI']).config(function ($routeProvider, $locationProvider) {

    //blockUIConfig.message = 'Please stop clicking!';
    //blockUIConfig.delay = 100;
    // Provide a custom template to use
    //blockUIConfig.templateUrl = '/Templates/block.html';
    //Path - it should be same as href link
    $routeProvider.when('/Admin/Accounts', { templateUrl: '/Templates/Accounts.html', controller: 'securityAccessController' })
                  .when('/Admin/ManageAccount', { templateUrl: '/Templates/ManageAccount.html', controller: 'manageAccountController' })
                  .otherwise({ redirectTo: '/Admin/ManageAccount' });
    $locationProvider.html5Mode(true);
});

//Customize the block UI look/message if this added
xxxxxxModule.config(function (blockUIConfig) {

    // Change the default overlay message
    blockUIConfig.message ="executing...";
    // Change the default delay to 100ms before the blocking is visible
    blockUIConfig.delay = 1;//.delay(1);
    // Disable automatically blocking of the user interface
    blockUIConfig.autoBlock = false;

});


xxxxxxModule.controller("manageAccountController", function ($scope, $location, xxxxxxService, blockUI) {
    //$scope.user = { Id: '0',Name:'New'  };
    $scope.showDelete = false;
    $scope.saveLabel = 'Create New User';
    //$scope.nameInfo = '';
    $scope.validationInfo = {};

    // Block the user interface
    blockUI.start();
    //$scope.blockUI_ = true;
    setTimeout(function () {
        xxxxxxxService.getAccounts().then(function (_users) {
            $scope.users = _users;
            $scope.user = { id: '-100', name: 'NEW' };
            $scope.users.unshift($scope.user);
            $scope.user = { Id: $scope.user.id, Name: $scope.user.name };
            securityAccessService.getEmployers().then(function (_employers) {
                $scope.employers = _employers;
                securityAccessService.getRoles().then(function (_roles) {
                    $scope.roles = _roles;
                    // Unblock the user interface
                    //setTimeout(function () { blockUI.stop(); }, 9000)
                    blockUI.stop();
                }, function ()
                { alert('error while fetching roles from server') });
            }, function ()
            { alert('error while fetching users from server') });


        }, function ()
        { alert('error while fetching users from server') });
    }, 9000);// for 1 and half minutes
});

xxxxxxModule.factory("xxxxxxService", function ($http, $q) {
    return {
        getAccounts: function () {
            // Get the deferred object
            var deferred = $q.defer();
            // Initiates the AJAX call
            $http({ method: 'GET', url: '/Admin/GetXXXXXDetails' }).success(deferred.resolve).error(deferred.reject);
            // Returns the promise - Contains result once request completes
            return deferred.promise;
        },
        getEmployers: function () {
            // Get the deferred object
            var deferred = $q.defer();
            // Initiates the AJAX call
            $http({ method: 'GET', url: '/Admin/GetXXXXXXXDetails' }).success(deferred.resolve).error(deferred.reject);
            // Returns the promise - Contains result once request completes
            return deferred.promise;
        },
        getRoles: function () {
            // Get the deferred object
            var deferred = $q.defer();
            // Initiates the AJAX call
            $http({ method: 'GET', url: '/Admin/GetXXXXDetails' }).success(deferred.resolve).error(deferred.reject);
            // Returns the promise - Contains result once request completes
            return deferred.promise;
        }
    }
});
And this is very important:
>@section customStyles{
    <link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet"></link>
    <link href="~/Content/angular-block-ui.css" rel="stylesheet"></link>
    }
@section customHeadJS
{
    <script src="~/Scripts/jquery-ui-1.10.4.min.js"></script>
    <script src="~/Scripts/angular.js"></script>
    <script src="~/Scripts/angular-ui/ui-utils.js"></script>
    <script src="~/Scripts/angular-route.js"></script>
    <script src="~/Scripts/angular-block-ui.js"></script>
}
<div ng-app="xxxxxxModule">

    <div class="container" block-ui="main" ng-class="{blockui:blockUI_==true}">
        <div class="navbar navbar-default">
            <div class="navbar-header">
                <ul class="nav navbar-nav">
                    <li class="navbar-brand"><a href="/Admin/Accounts">Members</a></li>
                    <li class="navbar-brand"><a href="/Admin/ManageAccount">Manager User</a></li>
                </ul>
            </div>
        </div>
        <div ng-view>
        </div>
    </div>
</div>
To use Jquery BlockUI instead:
    xxxApp.factory("validationService", function ($http, $q) {
        return {
            runValidation: function (member) {
                // Get the deferred object
                var deferred = $q.defer();                                
                $http({ method: 'POST', url: '/xxxProcess/Runxxxx', data: { xxxID: member.xxxId } }).success(deferred.resolve).error(deferred.reject);
                // Returns the promise - Contains result once request completes
                return deferred.promise;
            },
            displayBlock: function () {
                $.blockUI.defaults.css.border = 'hidden';//'2px solid black';
                $.blockUI.defaults.overlayCSS.backgroundColor = 'white';
                $.blockUI.defaults.overlayCSS.opacity = .6;
                $.blockUI({ message:'<h3><img src="/Images/busy.gif" /> Just a moment...</h3>' });
            },

            noMoreBlock: function () {
                $.unblockUI();
            }
        }
    });

..............

        $scope.runValidation = function (member) {
            validationService.displayBlock();
            validationService.runValidation(member).then(function (_data) {
                doSomethingHere(_data);
            }, function ()
            {
                alert('error while running Validation at server');
            }).finally(function () {
                $scope.getValidationErrors();
                validationService.noMoreBlock();
            });
            
        };

Saturday, October 25, 2014

Private Members in JavaScript

This is written by  Douglas Crockford

JavaScript is the world's most misunderstood programming language. Some believe that it lacks the property of information hiding because objects cannot have private instance variables and methods. But this is a misunderstanding. JavaScript objects can have private members. Here's how.

Objects

JavaScript is fundamentally about objects. Arrays are objects. Functions are objects. Objects are objects. So what are objects? Objects are collections of name-value pairs. The names are strings, and the values are strings, numbers, booleans, and objects (including arrays and functions). Objects are usually implemented as hashtables so values can be retrieved quickly.
If a value is a function, we can consider it a method. When a method of an object is invoked, the this variable is set to the object. The method can then access the instance variables through the this variable.
Objects can be produced by constructors, which are functions which initialize objects. Constructors provide the features that classes provide in other languages, including static variables and methods.

Public

The members of an object are all public members. Any function can access, modify, or delete those members, or add new members. There are two main ways of putting members in a new object:
In the constructor
This technique is usually used to initialize public instance variables. The constructor's this variable is used to add members to the object.
function Container(param) {
    this.member = param;
}
So, if we construct a new object
var myContainer = new Container('abc');
then myContainer.member contains 'abc'.
In the prototype
This technique is usually used to add public methods. When a member is sought and it isn't found in the object itself, then it is taken from the object's constructor's prototype member. The prototype mechanism is used for inheritance. It also conserves memory. To add a method to all objects made by a constructor, add a function to the constructor's prototype:
Container.prototype.stamp = function (string) {
    return this.member + string;
}
So, we can invoke the method
myContainer.stamp('def')
which produces 'abcdef'.

Private

Private members are made by the constructor. Ordinary vars and parameters of the constructor becomes the private members.
function Container(param) {
    this.member = param;
    var secret = 3;
    var that = this;
}
This constructor makes three private instance variables: paramsecret, and that. They are attached to the object, but they are not accessible to the outside, nor are they accessible to the object's own public methods. They are accessible to private methods. Private methods are inner functions of the constructor.
function Container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;
}
The private method dec examines the secret instance variable. If it is greater than zero, it decrements secret and returns true. Otherwise it returns false. It can be used to make this object limited to three uses.
By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.
Private methods cannot be called by public methods. To make private methods useful, we need to introduce a privileged method.

Privileged

privileged method is able to access the private variables and methods, and is itself accessible to the public methods and the outside. It is possible to delete or replace a privileged method, but it is not possible to alter it, or to force it to give up its secrets.
Privileged methods are assigned with this within the constructor.
function Container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;

    this.service = function () {
        return dec() ? that.member : null;
    };
}
service is a privileged method. Calling myContainer.service() will return 'abc' the first three times it is called. After that, it will return nullservicecalls the private dec method which accesses the private secret variable. service is available to other objects and methods, but it does not allow direct access to the private members.

Closures

This pattern of public, private, and privileged members is possible because JavaScript has closures. What this means is that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned. This is an extremely powerful property of the language. There is no book currently available on JavaScript programming that shows how to exploit it. Most don't even mention it.
Private and privileged members can only be made when an object is constructed. Public members can be added at any time.

Patterns

Public
function Constructor(...) {
this.membername = value;
}
Constructor.prototype.membername = value;
Private
function Constructor(...) {
var that = this;
var 
membername = value;function membername(...) {...}
}
Note: The function statement
function membername(...) {...}
is shorthand for
var membername = function membername(...) {...};
Privileged
function Constructor(...) {
this.membername = function (...) {...};
}


More About Object


Numbers, strings, and booleans are object-like in that they have methods, but they are immutable. Objects in JavaScript are mutable keyed collections. An object is a container of properties, where a property has a name and a value.

JavaScript’s fundamental datatype is the object. An object is a composite value: it aggregates multiple values (primitive values or other objects) and allows you to store and retrieve those values by name. An object is an unordered collection of properties, each of which has a name and a value. Property names are strings, so we can say that objects map strings to values. This string-to-value mapping goes by various names: you are probably already familiar with the fundamental data structure under the name “hash,” “hashtable,” “dictionary,” or “associative array.” An object is more than a simple string-to-value map, however. In addition to maintaining its own set of properties, a JavaScript object also inherits the properties of another object, known as its “prototype.” The methods of an object are typically inherited properties, and this “prototypal inheritance” is a key feature of JavaScript.

JavaScript objects are dynamic—properties can usually be added and deleted—but
they can be used to simulate the static objects and “structs” of statically typed languages. They can also be used (by ignoring the value part of the string-to-value mapping) to represent sets of strings.

Any value in JavaScript that is not a string, a number, true, false, null, or undefined is an object. And even though strings, numbers, and booleans are not objects, they behave like immutable objects .

Objects are mutable and are manipulated by reference rather than by value. If the variable x refers to an object, and the code var y = x; is executed, the variable y holds a reference to the same object, not a copy of that object. Any modifications made to the object through the variable y are also visible through the variable x.

The most common things to do with objects are create them and to set, query, delete, test, and enumerate their properties.

A property has a name and a value. A property name may be any string, including the
empty string, but no object may have two properties with the same name. The value 115 may be any JavaScript value, or (in ECMAScript 5) it may be a getter or a setter function (or both).  In addition to its name and value, each property has associated values that we’ll call property attributes:
• The writable attribute specifies whether the value of the property can be set.
• The enumerable attribute specifies whether the property name is returned by a
for/in loop.
• The configurable attribute specifies whether the property can be deleted and
whether its attributes can be altered.

Prior to ECMAScript 5, all properties in objects created by your code are writable,enumerable, and configurable. In ECMAScript 5, you can configure the attributes of your properties.

In addition to its properties, every object has three associated object attributes:
• An object’s prototype is a reference to another object from which properties are
inherited.
• An object’s class is a string that categorizes the type of an object.
• An object’s extensible flag specifies (in ECMAScript 5) whether new properties may
be added to the object.

Three broad categories of JavaScript objects and two types of properties:
• A native object is an object or class of objects defined by the ECMAScript specification.
Arrays, functions, dates, and regular expressions (for example) are native objects.
• A host object is an object defined by the host environment (such as a web browser) within which the JavaScript interpreter is embedded. The HTMLElement objects that represent the structure of a web page in client-side JavaScript are host objects. Host objects may also be native objects, as when the host environment defines methods that are normal JavaScript Function objects.
• A user-defined object is any object created by the execution of JavaScript code.
• An own property is a property defined directly on an object.
• An inherited property is a property defined by an object’s prototype object.

Friday, October 24, 2014

reset valid for all form controls

I was trying to set $valid for all form controls, however I googled around and I do not see any solution to this on the internet. And I came out this myself as below:
    $scope.clearValidation = function () {
        angular.forEach($scope.managerUserForm, function (value, key) {
            var type = $scope.managerUserForm[key];
            if (type.$error) {
                angular.forEach(type.$error, function (value, key) {
                    type.$setValidity(key, 'true');                    
                });
            }
        });
    };
Or use this in modern browsers with ECMAScript 5 foreach:
Object.keys($scope.managerUserForm).forEach(function (key) {
            var type = $scope.managerUserForm[key];
            if (type.$error) {
                Object.keys(type.$error).forEach(function (key) {
                    type.$setValidity(key, 'true');                    
                });
            }
});
Or use underscore:
_.each($scope.managerUserForm, function(value, key){
    var type = value;
    if (type.$error) {
     _.each(type.$error, function(value, key){
        type.$setValidity(key, 'true'); 
     });
   }
});

Thursday, October 23, 2014

ng-readonly : Token '-100' is an unexpected token at column 10 of the expression

Token '-100' is an unexpected token at column 10 of the expression [user.Id!=='-100'] starting at ['-100'
 
 
ng-readonly="user.Id!=='-100'"
 
The issue disappears if the code changes to
 
    ng-readonly="user.Id!='-100'"
 Or ng-readonly="user.Id!==-100"

The reason?

ng-readonly or ng-show takes an "AngularJS statement." This type of statement only has an == operator, but this operator behaves like ===. It's a bit confusing.

Type coercion means that when the operands of an operator are different types, one of them will be converted to an "equivalent" value of the other operand's type. For instance, if you do:
boolean == integer
the boolean operand will be converted to an integer: false becomes 0true becomes 1. Then the two values are compared.
However, if you use the non-converting comparison operator ===, no such conversion occurs. When the operands are of different types, this operator returns false, and only compares the values when they're of the same type.

Tuesday, October 14, 2014

ORA-01722: invalid number - Parameters should always be added in order

I got this error while run the update statement.

The issue is due to the order while adding parameters not consistent with the order of the sql.
        const string UpdateXXXXXXXQuery = @"UPDATE XXXXXXX
                                                    SET STATUS           = :v_STATUS,
                                                    STATUSDATE       = SYSDATE,
                                                    STATUSUPDATEUSER = :v_USER                            
                                                    WHERE COLYEAR        = :v_YEAR
                                                    AND EMPLOYERNUMBER   = :v_EMPLOYER";
Parameters should always be added in the order of the sql
            OracleCommand cmd = new OracleCommand();
            OracleDataReader odr = null;
            cmd.Connection = dataDBConnection;
            cmd.CommandText = UpdateXXXXXXXQuery;
            cmd.CommandType = CommandType.Text;
            cmd.Prepare();
            cmd.Parameters.Clear();
            cmd.Parameters.Add("v_STATUS", "SUBMITTED");//1st
            cmd.Parameters.Add("v_USER", userLogin);//2nd
            cmd.Parameters.Add("v_YEAR", OracleDbType.Int32, DateTime.Now.Year, ParameterDirection.Input);//3rd
            cmd.Parameters.Add("v_EMPLOYER",OracleDbType.Int32,  employerID,ParameterDirection.Input);//4th            
            cmd.ExecuteNonQuery();
            cmd.Dispose();

Monday, October 13, 2014

Creating Shorthand/Literal Values from Constructors

JavaScript provides shortcuts—called “literals”—for manufacturing most of the native object values without having to use new Foo() or new Bar(). For the most part, the literal syntax accomplishes the same thing as using the new operator. The exceptions are: Number(), String(), and Boolean()

var myRegExp = new RegExp('\bt[a-z]+\b');
var myRegExpLiteral = /\bt[a-z]+\b/;

var myObject = new Object();
var myObjectLiteral = {};

var myArray = new Array('foo', 'bar');
var myArrayLiteral = ['foo', 'bar'];

var myFunction = new Function("x", "y", "return x*y");
var myFunctionLiteral = function(x, y) {return x*y};

var myFunction = new Function();
var myFunctionL = function() {}; // literal shorthand

var myObject = new Object();
var myObjectL = {}; // literal shorthand
var myArray = new Array();
var myArrayL = []; // literal shorthand

var myNumber = new Number(23); // an object
var myNumberLiteral = 23; // primitive number value, not an object

var myString = new String('male'); // an object
var myStringLiteral = 'male'; // primitive string value, not an object

var myBoolean = new Boolean(false); // an object
var myBooleanLiteral = false; // primitive boolean value, not an object
var CustomConstructor = function CustomConstructor(){ return 'Wow!'; };
var instanceOfCustomObject = new CustomConstructor();
// logs true
console.log(instanceOfCustomObject.constructor === CustomConstructor);
// returns a reference to CustomConstructor() function
// returns 'function() { return 'Wow!'; };'
console.log(instanceOfCustomObject.constructor);

using literals simply conceals the underlying process identical to using the new operator. Maybe more importantly, it’s a lot more convenient!

JavaScript Enlightenment :
When using literal values for string, number, and boolean, an actual complex object is never created until the value is treated as an object. In other words, you are dealing with a primitive datatype until you attempt to use methods or retrieve properties associated with the constructor (e.g., var charactersInFoo = 'foo'.length). When this happens, JavaScript creates a wrapper object for the literal value behind the scenes, allowing the value to be treated as an object. Then, after the method is called, JavaScript discards the wrapper object and the value returns to a literal type. This is why string, number, and boolean are considered primitive (or simple) datatypes. I hope this clarifies the misconception that “everything in JavaScript is an object” with the concept that “everything in JavaScript can act like an object.”

When a primitive value is used as if it were an object created by a constructor, JavaScript converts it to an object in order to respond to the expression at hand, but then discards the object qualities and changes it back to a primitive value.

// Produce primitive values
var myNull = null;
var myUndefined = undefined;
var primitiveString1 = "foo";
var primitiveString2 = String('foo');//did not use new, so we get primitive
var primitiveNumber1 = 10;
var primitiveNumber2 = Number('10');//did not use new, so we get primitive
var primitiveBoolean1 = true;
var primitiveBoolean2 = Boolean('true');//did not use new, so we get primitive
/* Access the toString() property method (inherited by objects from
object.prototype) to demonstrate that the primitive values are converted to
objects when treated like objects. */
// logs "string string"
console.log(primitiveString1.toString(), primitiveString2.toString());
// logs "number number"
console.log(primitiveNumber1.toString(), primitiveNumber2.toString());
// logs "boolean boolean"
console.log(primitiveBoolean1.toString(), primitiveBoolean2.toString());
/* This will throw an error and not show up in firebug lite, as null and
undefined do not convert to objects and do not have constructors. */
console.log(myNull.toString());
console.log(myUndefined.toString());


Math is a static object—a container for other methods—and is not a constructor that uses the new operator

It’s possible to forgo the use of the new keyword and the concept of a constructor function by explicitly having the function return an object. The function would have to be written explicitly to build an Object() object and return it:
var myFunction = function(){
return {prop: val}
};
Doing this, however, sidesteps prototypal inheritance.

Wednesday, October 8, 2014

Oracle: An attempt was made to modify an object, REF, VARRAY, nested table, or LOB column type

Here is what you can do to change a column of type VARCHAR2(4000) to a CLOB since you will get the error if simply using 'alter table EMAIL modify (TEMPLATE_CONTENT clob)':

alter table EMAIL  add (temp clob);

update EMAIL set temp=EMAIL_BODY, EMAIL_BODY=null;

alter table EMAIL drop column EMAIL_BODY;
alter table EMAIL rename column temp to EMAIL_BODY;