Should I use Typescript

 

Typescript is a stone’s throw from 1.0 today. Here are the answers I need to make my decision:

  1. How to use it with AngularJS
    1. http://www.nuget.org/packages/angularjs.TypeScript.DefinitelyTyped/
    2. Is typescript open source ?
      1. Yes : https://typescript.codeplex.com/
      2. typescript for windows 8 apps
        1. http://blogs.msdn.com/b/yizhe/archive/2012/11/22/getting-started-typescript-for-windows-8-projects-using-visual-studio-2012.aspx
        2. http://elegantcode.com/2013/11/29/convert-an-existing-winjs-app-to-use-typescript/
        3. vs Traceur
        4. Does it work for node apps
          1. npm install -g typescript
          2. Will it help me learn ES6
            1. Yes, coz for debugging I’ll be looking at JS code and so will have to understand what TS code compiles to what JS and how and why

Note:

Set the “Generate Source Map” to True in the Visual Studio options to create source maps between TypeScript and JavaScript to enable TypeScript debugging. This option applies the –sourcemap compiler switch, which in turn creates the maps at compile time.

The TypeScript compiler by default compiles to ECMAScript 3 (ES3)-compliant code; however, you can compile to ECMAScript 5 (ES5) if you change the “Compile to ECMAScript 3” option to False in Visual Studio, which sets the tsc compiler flag –target to generate ES5 code. Developers who want to use property-style syntax or any ES5 or proposed ES6 TypeScript features should set this switch.

 

I’m ready to start now. Off to: http://www.typescriptlang.org/

Egghead Angular

 

  1. $scope is not model, just the ref to stuff in the div of controller
  2. Ng-model inside ng-app but not in any controller is part of $rootScope
  3. Svc define with Svc case
  4. myApp.factory(‘Data’, function() {

return(message: “Hello”); }

function myCtrl($scope, Data) {

$scope.Data = Data;

}

  1. In svc always pass the data as taking it from scope is not ideal for reusabilty
  2. Convert Svc to Filter whenever needed and simply put the svc code in A

Here: myApp.filter (‘reverse’, function() {a})

  1. Use inbuild filters like Filter and OrderBy
    1. Filter: $ for all
    2. orderBy:’-name’
    3. limitTo:5 or -5
    4. USE PIPING IN FILTERS
    5. Lowercase
    6. Use the JQLite features like element.bind(“mouseenter”) etc.
    7. Create Directive Behaviors for events etc
    8. IF A MODULE HAS A CONTROLLER AND A DIRECTIVE, THEN THEY MAY NOT SHARE SCOPE AND HENCE KEEP THEM SEPARATE BY EXPLICITLY PASSING DATA FROM CONTROLLER TO DIR
    9. USE SCOPE.$APPLY(“FUNCTION NAME”) AND IN THE DIR DECLERATION <div myDirective=”deleteTweets()”>, this string will go In attr of the dir and apply: scope.$apply(attr.mydirective)
    10. U can define the controller within the directive also
    11. When sharing data b/w directives, the parent can act as API and expose functions, But note that u should create scope of parent as Isolate using scope: {} so that child can’’t override it.
    12. But if u do scope: {}, then it will not be shared with the controller of this dir as well. For that,  in dir do done: choredone() and in scope say done:”&” //meaning expression ie u can say: done = “logChore(chore)” and then ng-clk= “done({chore:chore})”

Browser Slideshow App

I recently created a Web Client that switches between configured Web Pages, switching each page after user configured time :

The workflow is like this:

1. Admin Configures the URLs and time using the Admin Page (RefreshAdmin.html)

2. He then launches the slideshow on a projector or such… (Slideshow.html)

3. The person passing by notices a Page and wants to read it

4. When he reaches his desk, he opens a web page that shows all articles/pages that the slideshow is looping (RefreshForU.html)

5. He then searches for the page he wants and reads it…

Technology Used:

1. Server Side: Asp.Net MVC4 webAPI

2. Client Side: JQuery, Bootstrap, AngularJS

The code is shared here.

 

PS..

Here’s how i was planning to do it bfr:

My aim is to create a webpage that would embed different sites using an iframe and hence display varied content .

I thought that doing this either through html or javascript would be straightforward, but I was mistaken.

For all sites I got this error http://stackoverflow.com/questions/6666423/overcoming-display-forbidden-by-x-frame-options and its resolution is really screwed up and also different for different sites

Anyways, now I’ve decided to launch new windows in fullscreen and display all the content instead.

window.open(URL,name,specs,replace)

From <http://www.w3schools.com/jsref/met_win_open.asp>

https://developer.mozilla.org/en-US/docs/Web/API/window.close

Lessons and Tips in JAVASCRIPT (angular and jquery)

1.       I started with creating a form in HTML and on submit clk, POSTing the data to DB and on success GETing all data from DB to show in ng-grid.

a.       This was a nice experience except that I had to make my scope objects global in
order to update the data (MyData) from non Angular code

b.      I later changed this simply by making all code fall inside my controller and
hence no need for global scope.

c.       This is my grid config:

$scope.gridOptions = {

        data: ‘myData’,

        columnDefs: columnDefs,

        multiSelect: false,

        selectedItems: selItems,

        enableCellSelection: true,

        enableRowSelection: true,

        enableCellEdit: true,

    };

The reason the I kept multiSelect: false

Is coz otherwise the behavior was erratic, meaning that If user selects 1 row and then deselects it and selects another then the selItems[] used to contain all items.
Also I had to empty the array after each use (selItems = [];) otherwise it used to keep appending new selectionsto the same one.

 

 

2.  For  columnDefs I gave % widths:

 

columnDefs = [{ field: ‘CollegeName’, displayName: ‘College Name’, width: “20%”, resizable: true }, { field: ‘TeamName’, displayName: ‘Team Name’, width: “20%”, resizable: true }…

 

 

3.       Since my JSON was an Array string (each string containing the entire object), I was
unable to parse it into Array of Objects directly. Instead I had to do it this
way:

 var myclients = new Array();
                var i = 0;
                while (i < data.length) {
                    myclients[i] = JSON.parse(data[i]);// data[i] eg: ‘{CollegeName:10, TeamName:”test”}’
                    i++;
                }
                $scope.myData = myclients;

4.       For ajax call from angular I used $http and from non angular code I used $ajax

5.       Validate JSON:

 if (/^[\],:{}\s]*$/.test(jsonData.replace(/\\[“\\\/bfnrtu]/g‘@’).

                    replace(/”[^”\\\n\r]*”|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g‘]’).

                    replace(/(?:^|:|,)(?:\s*\[)+/g))) {

alert(‘the json is VALID’);

 } else {
                     alert('the json is INVALID');
                 }

 

6. When I get the response from MVC WebApi as a JSON object, I still tried
to JSON.parse() it and it kept failing until I realized that JSON.parse is only
used to parse JSON objects that are inform of JSON strings :Eg:

var a= {CollegeName:10, TeamName:’test’}

undefined

var b = JSON.stringify(a)

undefined

b

{“CollegeName”:10,”TeamName”:”test”}

var c = b

undefined

typeof(c)

string

typeof(b)

string

typeof(a)

object

var d = JSON.parse(c)

undefined

d

Object {CollegeName: 10, TeamName: “test”}

typeof(d);

object

Hence use JSON.parse
i.e. Deserialize for objects serialized using JSON.stringify

But
on the .Net side of things, the story is that when u send a put request, u have
to send data in form of String:

var jsonData = JSON.stringify(entry);
                
                if (/^[\],:{}\s]*$/.test(jsonData.replace(/\\["\\\/bfnrtu]/g'@').
                    replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g']').
                    replace(/(?:^|:|,)(?:\s*\[)+/g''))) {

                    $.ajax({
                        type: "PUT",
                        url: "http://localhost/..." + querystring,
                        data: { "": jsonData },
                        success: function(result) {
                            //getConfig();
                            $scope.updateData();
                        }
                    });

                } else {

                    alert('the json is INVALID');

                }

In this case the
data: is in a weird object with a prop with no name ..but this is how it works
in case of PUT and POST requests..

Now in .net side
it gets the same string jsonData, which u can de-serialize using
newtonsoftJSON.

 

7.       Another thing that I was trying to do
is to serialize response, until I realized that MVC4 webAPI will automatically
do that for me and all I have to do is to return my object or string or
collection…

8.       Migrating
non Angular stuff to angular:

a.       Except
for ng-grid in one cell of table on page rest all was pure html

b.      But
on adding controller at ng-grid level or cell, it didn’t work

c.       So
I put it at the Body level

d.      This
allowed me to put all non angular functionality in the controller as now $scope
is available in the whole HTML Body.

e.      So I
changed function getConfig() {} to $scope.getConfig = function() {}

f.
Then I canged its call to getConfig ()

g.       So
all code was now here:

var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl'function ($scope, $http) {

//All Code

}

That’s all really

1.     Javascript forEach:

selItems.forEach(function(entry) { });

2.
JQuery ajax sample:

                $.ajax({

                    type: “DELETE”,

                    url: http://localhost/…&#8221;,

                    success: function(result) {

                        //alert(result.toString());

                        $scope.updateData();

                    },

                     error: (function (result) {
                     alert("Error Occurred");
                     })

                });

Angular tips and Tricks

1.       $http

 $http({ method: ‘GET’, url: http://localhost/GameAdmin/api/Values&#8217; })

            .success(function(data, status, headers, config) {

 

            });