Thursday, November 27, 2014

SignalR note

The following lists the important points for server side here:
  • SignalR 2.0 uses Open Web Interface (OWIN) for .NET as the standard interface between .NET web servers and web applications, enabling a level of indirection and abstraction that keeps your project from directly tying to any specific hosting platform. This is the technical foundation that actually enables SignalR to be hosted from both web applications and traditional .NET processes, as we'll see later.
  • Every OWIN application must have a Startup class that follows specific conventions. In particular, a Configuration() method with the signature shown in the preceding code must be made available.
  • The assembly-level attribute OwinStartup is there to declare that our Startup class will be used to bootstrap every OWIN-based asset contained in all the loaded assemblies; there are other ways to declare the right Startup class to load, but we'll see them in the future recipes.
  • Inside the Configuration() method, we start up SignalR using an appropriate extension method (MapSignalR()) made available by the SignalR core inside the Owin namespace; a call to the MapSignalR() method will expose an endpoint called /signalr, which the clients will use to connect to the server.
The main points of client side scripts:
  • Add a Hub class. Any class available in the project that is derived from Hub is automatically discovered and exposed when SignalR is initialized calling MapSignalR in the Startup class.
  • The client page established a connection to the Hub using the JavaScript SignalR client library.
  • When the connection is ready, make a remote call to the xxx() method exposed by the custom Hub.
  • SignalR coordinates the two sides using the most appropriate connection strategy taking into account which is the HTTP server hosting the application and which web browser is used to run the client page; it gives us the feeling of a direct connection towards our server-side Hub, allowing us to call methods on it directly (the line hub.server.xxx('xxx SignalR!');).

Friday, November 14, 2014

functional Javascript

A few good stuff online:

functional-javascript

Functional is a library for functional programming in JavaScript.

JavaScript Allongé

functional.js is a functional JavaScript library. It facilitates currying and point-free / tacit programming and this methodology has been adhered to from the ground up

The function existy is meant to define the existence of something. JavaScript has two values—null and undefined—that signify nonexistence. Thus, existy checks that its argument is neither of these things, and is implemented as follows

function existy(x) { return x != null }; 
Using the loose inequality operator (!=), it is possible to distinguish between null, undefined, and everything else. It’s used as follows
existy(null);
//=> false
existy(undefined);
//=> false
existy({}.notHere);
//=> false
existy((function(){})());
//=> false
existy(0);
//=> true
existy(false);
//=> true
The use of existy simplifies what it means for something to exist in JavaScript. Minimally, it collocates the existence check in an easy-to-use function. The second function mentioned, truthy, is defined as follows
function truthy(x) { return (x !== false) && existy(x) };
The truthy function is used to determine if something should be considered a synonym for true, and is used as shown here
truthy(false);
//=> false
truthy(undefined);
//=> false
truthy(0);
//=> true
truthy('');
//=> true
In JavaScript, it’s sometimes useful to perform some action only if a condition is true and return something like undefined or null otherwise. The general pattern is as follows:
{
if(condition)
return _.isFunction(doSomething) ? doSomething() : doSomething;
else
return undefined;
}
Using truthy, I can encapsulate this logic in the following way
function doWhen(cond, action) {
if(truthy(cond))
return action();
else
return undefined;
}
Now whenever that pattern rears its ugly head, you can do the following instead

function executeIfHasField(target, name) {
return doWhen(existy(target[name]), function() {
var result = _.result(target, name);
console.log(['The result is', result].join(' '));
return result;
});
}
The execution of executeIfHasField for success and error cases is as follows:
executeIfHasField([1,2,3], 'reverse');
// (console) The result is 3, 2, 1
//=> [3, 2, 1]
executeIfHasField({foo: 42}, 'foo');
// (console) The result is 42

Wednesday, November 12, 2014

bootstrap collapse

The script below is for icon toggling:
                $scope.collapseBar = function (ev, id) {
            var _toggleClass = function (elem, parent) {                 
                var _toggle_full = 'glyphicon-resize-full',id,
                    _toggle_small = 'glyphicon-resize-small',
                    _memberEvent_prefix = '#Panel_MemberEvents_Collapse_';
                if (id) _id = _memberEvent_prefix + id;
                if (elem.hasClass(_toggle_full) || elem.hasClass(_toggle_small)) {                    
                    elem.toggleClass(_toggle_full + ' ' + _toggle_small);                    
                    if (_id) $(_id).toggleClass('in');
                    return true;
                }
            }

            if (ev && ev.target) {
                $(ev.target).each(function () {
                    if (_toggleClass($(this), true)) return;
                    else if ($(this).children().length > 0) {
                        $(this).children().each(function () {
                            _toggleClass($(this));
                        });
                    }
                });
            }
        };

And the html mark up:
<!DOCTYPE html>

<html>

<head>

  <title>Twitter Bootstrap : Collapsible Accordion</title>

<link rel="stylesheet"

      href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">

<link rel="stylesheet"

     href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap-theme.min.css">

<script src="http://code.jquery.com/jquery.min.js"></script>

<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>

</head>

<style>

.DemoBS2{

    margin:20px;

}

</style>

<body>

<div class="DemoBS2">

<div class="panel-group" id="memberDetail-collapseTitle">

      <div class="panel panel-primary">

        <div class="panel-heading">
          <h4 class="panel-title">
          Collapsible Accordion 1
<span class="pull-right">


                    <a data-toggle="collapse" ng-click="collapseBar($event)" data-parent="#memberDetail-collapseTitle"


                       href="#memberDetail-collapse">


                        <span class="btn btn-default btn-sm" title="Collapse">


                            <span class="glyphicon glyphicon-resize-small"></span>


                        </span>


                    </a>


                </span>


          </h4>

        </div>

        <div id="memberDetail-collapse" class="panel-collapse collapse in">

          <div class="panel-body">

         something here to expand or collapse ....
            </div>

        </div>

      </div>

      <div class="panel panel-success">

        <div class="panel-heading">

          <h4 class="panel-title">

           the title to show here <span class="pull-right commandIcons">


                <span data-href="#memberDetail-collapse" onclick="g_collapseBar($(this))" class="caatCollapse btn btn-default btn-sm" ng-disabled="isReadonly">


                    <span class="glyphicon glyphicon-resize-full"></span>


                </span>


            </span>


          </h4>

        </div>

        <div id="accordionTwo" class="panel-collapse collapse">

          <div class="panel-body">

            Change does not roll in on the wheels of inevitability,

            but comes through continuous struggle.

            And so we must straighten our backs and work for

            our freedom. A man can't ride you unless your back is bent.

      </div>

        </div>

      </div>

      <div class="panel panel-warning">

        <div class="panel-heading">

          <h4 class="panel-title">
ADASDASFDSFDS
            <span class="pull-right">
                <button data-targetpanel="#memberDetail-collapse" onclick="return collapseBar($(this));" class="btn btn-default btn-sm" title="Expand or collapse">
                    <span class="glyphicon glyphicon-resize-small"></span>
                </button>
            </span>

          </h4>

        </div>



        <div id="accordionThree" class="panel-collapse collapse">

          <div class="panel-body">

          You must take personal responsibility.

            You cannot change the circumstances,

            the seasons, or the wind, but you can change yourself.

            That is something you have charge of.

      </div>

        </div>

      </div>

    </div></div>

</body>

</html>

And Jquery toggle API, with no parameters, the .toggle() method simply toggles the visibility of elements:
$( ".target" ).toggle();

Collapse and Expand using JQuery toggle():
    g_collapseBar = function (element) {
        var $t = element;//$(this);
        var _toggle_full = 'glyphicon-resize-full',
                _toggle_small = 'glyphicon-resize-small';
        $($t.attr("data-href")).slideToggle();       
        $t.find('span.glyphicon').toggleClass(_toggle_full).toggleClass(_toggle_small);
    };

    collapseBar = function ($t) {
        $($t.attr("data-targetPanel")).slideToggle();
        $t.find('span.glyphicon').toggleClass('glyphicon-resize-full').toggleClass('glyphicon-resize-small');
        return false;
    };

Thursday, November 6, 2014

to load external Javascript on browser console

var el = document.createElement("script"),
loaded = false;
el.onload = el.onreadystatechange = function () {
  if ((el.readyState && el.readyState !== "complete" && el.readyState !== "loaded") || loaded) {
    return false;
  }
  el.onload = el.onreadystatechange = null;
  loaded = true;
  // done!
};
el.async = true;
el.src = '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js';
var hhead = document.getElementsByTagName('head')[0];
hhead.insertBefore(el, hhead.firstChild);

Tuesday, November 4, 2014

JavaScript: add months to a date handling edge cases (leap year, shorter months, etc)

Slip from dateJS:
Date.isLeapYear = function (year) {
       return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
};

Date.getDaysInMonth = function (year, month) {
    return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};

Date.prototype.isLeapYear = function () {
    var y = this.getFullYear();
    return (((y % 4 === 0) && (y % 100 !== 0)) || (y % 400 === 0));
};

Date.prototype.getDaysInMonth = function () {
    return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
};

Date.prototype.addMonths = function (value) {
   var n = this.getDate();
   this.setDate(1);
   this.setMonth(this.getMonth() + value);
   this.setDate(Math.min(n, this.getDaysInMonth()));
   return this;
};

Or using moment.js:
moment().add('months',1).format('YYYY-MM-DD');
moment().add('months',1).calendar();
moment().subtract('days', 1).calendar();
moment("20111031", "YYYYMMDD").fromNow(); // x years ago
moment("20120620", "YYYYMMDD").fromNow(); // x years ago
moment().startOf('day').fromNow();        // x hours ago
moment().endOf('day').fromNow();          // in xx hours
moment().startOf('hour').fromNow();     // xx minutes ago