Real Time Communication over the Web (Web RTC)

There are a lot of techniques for doing Web RTC, most of

which come under the umbrella term COMET.

For my project I used 2 such techniques:

1.      Forever Iframe

               In this, the client creates a hidden iFrame
on the page and sets its source as the remote resource (svc) that then keeps
pushing the messages to the iFrame within the script tag.

var iframeDoc = new ActiveXObject(“htmlfile”);

var  abc = “”;

var cid = guid();                 

iframeDoc .open();

abc = “<html><script>” + “document.domain = ‘” +  domain + “‘;function callback(x){//do
something}”
 + “</script>” + 

 + “</html>”;

iframeDoc.write(blah);

iframeDoc.parentWindow.a = a;

setInterval( function () {}, 100000);

transferDoc.close();

2.       Server Sent Event

if (window.EventSource === undefined) {

                                            notify(“Server Side Events
not Supported”
);

                                   }                         var Esource = new EventSource(http://abc/p/q&#8217;);

                                   Esource.onopen = function (event) {

                                            alert(“Connection Open”);

                                   };

                                   source.onerror = function (event) {                                            if (event.eventPhase === EventSource.CLOSED) {

                                                    alert(“Connection Close”);

                                            }

                                   };

                                   source.onmessage = function (event) {

                                            alert(event.data);

                                   };

Generate GUID in JavaScript:

var base = function () {
                  return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
         };
         var guid = function () {
                 return base() + base() + '-' + base() + '-' + base() + '-' + base() + '-' + base() + base() + base();
         };

 

 

–>

Advertisements

JQUERY Tips and Tricks.htm

1.    Delete all Rows of HTML Table: $(“table”).find(“tr:gt(0)”).remove();

2.     Add rows
to HTML Table

var tr;

            for (var i = 0; i < data.length; i++) {

                tr = $(‘<tr/>’);

                tr.append(“” + data[i].Key + “”);

                tr.append(“” + data[i].Value + “”);

                $(‘table’).append(tr);

            }

 
3.  Hide:$('#responseData').hide();

4.
Read a local resource: Give url:
“sites.xml”,

 

 

$(document).ready(function(){

                                        $.ajax({

                                                        type:
“GET”,

                                                        url:
“sites.xml”,

                                                        dataType:
“xml”,

                                                        success:
function(xml) {

                                                                        $(xml).find(‘site’).each(function(){

                                                                                        var
id = $(this).attr(‘id’);

                                                                                        var
title = $(this).find(‘title’).text();

                                                                                        var
url = $(this).find(‘url’).text();

                                                                                        $(‘<div
class=”items”
id=”link_’+id+'”></div>’).html(‘<a
href=”‘+url+'”>’+title+”).appendTo(‘#page-wrap’);

                                                                                        $(this).find(‘desc’).each(function(){

                                                                                                        var
brief = $(this).find(‘brief’).text();

                                                                                                        var
long = $(this).find(‘long’).text();

                                                                                                        $(‘<div
class=”brief”>’).html(brief).appendTo(‘#link_’+id);

                                                                                                        $(‘<div
class=”long”>’).html(long).appendTo(‘#link_’+id);

                                                                                        });

                                                                        });

                                                        }

                                        });

                        });

This is the xml:

<?xml version=”1.0″ encoding=”iso-8859-1″?>

 <sites>

   <site id=”0″>

     <title>Think2Loud</title>

                <url>http://www.think2loud.com</url&gt;

     <desc>

       <brief>this is the brief description.</brief>

       <long>…and this is the long description.  See how long
it is :)</long>

     </desc>

   </site>

   <site id=”2″>

5.       AngularJS
Instant search
: http://tutorialzine.com/2013/08/learn-angularjs-5-examples/

 

1.  Hide all:  $("textarea[id^='Details']").hide(); 
2.  Apply Css to all: $("div[id^='Panel']").css('margin', 35 + 'px');
3.  Add html : $("input[id^='TBStatus']").before("<img id='loadingImg' src='Assets\\LoadingS.gif' />");
4.  In case the position needs to be made constant: $("#CheckAll").css("right""20px").css("position""absolute");
5.  Change body color: $('body').css('background-color''Azure');
 
Rotate Image on clk by 180 degree and then back 180 degree on 2nd clk (eg. When u want to change the expander button to ^ on clk) WITH ANIMATION
A.  One way of doing this is to have 2 classes (1 to rotate 180deg and other to rotate back) and add class to html element on clk:
$('.rotate').click(function () {
        $(this).toggleClass('rotated');
    }); 
 

                              And in css

                .rotate
        {
            -webkit-transition-duration0.8s;
            -moz-transition-duration0.8s;
            -o-transition-duration0.8s;
            transition-duration0.8s;
            -webkit-transition-property-webkit-transform;
            -moz-transition-property-moz-transform;
            -o-transition-property-o-transform;
            transition-propertytransform;
            overflowhidden;
        }
        
        .rotate.rotated
        {
            -webkit-transformrotate(180deg);
            -moz-transformrotate(180deg);
            -o-transformrotate(180deg);
            -ms-transformrotate(180deg);
        }

6.
Call remote methods: This can be done in 2 ways,

a.    1st
that u have a restful svc like a webAPI that binds every HTTP verb to a method

b.    2nd in
other cases like mine, where I had a simple asp.net web app, my home.aspx was
calling svc.aspx and passing the method to be executed as  a “action” query
string : AJAXResponse.aspx?action=btn1_Clk&ID=” + iD;

Now in the c# code, in case u have
called
AJAXResponse.aspx,
then in it’s Page_Load(), check the action and call the method:

string action = HttpContext.Current.Request["action"];

            if (action == " btn1_Clk")
            {
                string ID = HttpContext.Current.Request["iD"];
                if (ID != null)
                    btn_Clk(ID);
            }

7.
Applying Gradient : Eg.

PASS
 $("#TBStatus" + BtnId).css('background-color''LightGreen');//.css({ background: "-webkit-gradient(linear, left top, left bottom, from(#ccc), to(#728C00))" }).css('font-weight', 'bold');  
   FAIL
   $("#TBStatus" + BtnId).css('background-color''Red');//.css({ background: "-webkit-gradient(linear, left top, left bottom, from(#ccc), to(#FF0000))" }).css('font-weight', 'bold');
 
8.  Unable to locate the exact element, use .prev() or .next()
9.  Common css:    css("visibility""visible"); .css("text-align""center")
10.Do a .trim() when assigning response JSON to js object ie deserializing or even when serializing etc.
11.id = String.fromCharCode(id.charCodeAt() + 1) //Eg of string manipulation
12.ID of btn in its event handler:  var id = event.currentTarget.id;
13.Show/hide panel on clk: TxtBoxId = event.currentTarget.id + "Text";$('#' + TxtBoxId).toggle('slow, linear'); 
14. 

Designing Functions:

The key is to start writing
everything in one function and then moving everything that u reuse to another
function such that no 2 lines of code are the same in the end….

 

 

–>

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

Pattern Matching in c#

1 .Read the xml file

System.IO.StreamReader stream = new System.IO.StreamReader(“config.xml”);PopMatcherFactoryInterface ConfigReader = new PopMatcherFactoryDefaultImpl();

SimplePatternsList = ConfigReader.LoadConfig(stream); // Patterns to match

 

2. Read the files

private static string DirectoryLookupPath = “C:\\”;string[] fileEntries = Directory.GetFiles(@DirectoryLookupPath);

//next use streamWriter to write the files

3 .Use RegEx to match the patterns

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) {

 

            });

Lessons and Tips in HTML

 

1.       I Always use Bootstrap for css. Even though I always have to edit their css file for my
customizations.

2.       Put custom script (<script src=”AdminPanel.js”></script>)at
the end after Jquery and Angular.

3.  <body ng-controller="MyCtrl" style="text-aligncenter">
4.   Bootstrap table sample code (ref : http://getbootstrap.com/2.3.2/base-css.html#tables):
 
<table width="100%" style="text-aligncenterpositionrelativemarginautomargin-top20px;" class="table table-striped table-bordered table-condensed">
<thead>
            <tr style="text-aligncenter">
                <th id="ClientList">Game Clients</th>
                <th id="AddClients">Add Clients</th>
            </tr>
        </thead>
        <thead>
        </thead>
        <tbody>
            <tr>
                <td width="50%" align="center">
                    <div
                        class="gridStyle" ng-grid="gridOptions" style="widthinheritheightinheritmin-height500pxmin-width750px;">
                    </div>

6.
Bootstrap form sample code (generated using http://minikomi.github.io/Bootstrap-Form-Builder/).

 <fieldset>

 

                        <!– Form Name –>

                        <legend>Register New Client</legend>

 

                        <!– Text input–>

                        <div class=”control-group”>

                            <label class=”control-label” for=”CollegeName”>College Name: </label>

                            <div class=”controls”>

                                <input id=”CollegeName” name=”CollegeName” type=”text” placeholder=”Name of College” class=”input-xlarge” required=””>

                            </div>

                        </div>

7.       Note that don’t use the form submit button from http://minikomi.github.io/Bootstrap-Form-Builder/
as it’ll make call to backend to post data. Instead use a normal Button if u
want ur handler to get invoked..

                        <!-- <!-- Button -->
                        <div class="control-group">
                            <label class="control-label" for="Submit"></label>
                            <div class="controls">
                                <button id="Submit" name="Submit" ng-click="postSingleConfig()">Register</button>
                            </div>
                        </div>

 

 

–>

Lessons and Tips in MVC4

Recently i had to create a JSON client MVC4 webapi.

The client had to show the JSON response in a list and allow for CRUD operations on all records.

For this i decided to use ng-grid for the Table.

Main problems that i had was to create the JSON request object and response, as my requirement of storing the record as a JSON string in SQL Compat DB did nto allow me to deserialize the whole thing into an object and instead i had to do string manipulation (I tried doing dynamic d = JObject.Parse(value); but it didn’t work out well)

On .Net side i used NewtonSoft.Json. 

Lessons and Tips in MVC4

  1. MVC Controller (and Newsoft.Json) creates a JSON array for C# collections and  a JSON object for c# Objects. This was an issue for me as on the client side Objects are a better fit. Hence I later created a simple Object containing a string property to send over Objects instead of Array of strings as JSON.
  2.      For each record I needed a unique identifier, for which I created a GUID() to return (new Random()).Next(10000000, 99999999);. But the problem with this was that if I called this in a loop the no. generated were the same which is not acceptable in a GUID. Hence I then used sleep() to give lag, and later started ccomparing new GUID will all others to check for duplicate. But I then found c#’s GUID which worked best for me.
  3.    Use enums for all constant value sets as I found that spelling/case mistakes can happen in user I/P rendering the DB Corrupt.