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
 + “</script>” + 

 + “</html>”;


iframeDoc.parentWindow.a = a;

setInterval( function () {}, 100000);


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



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();





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 + “”);



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

Read a local resource: Give url:








function(xml) {


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

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

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



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

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








This is the xml:

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


   <site id=”0″>




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

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



   <site id=”2″>

5.       AngularJS
Instant search


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

                              And in css


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

Applying Gradient : Eg.

 $("#TBStatus" + BtnId).css('background-color''LightGreen');//.css({ background: "-webkit-gradient(linear, left top, left bottom, from(#ccc), to(#728C00))" }).css('font-weight', 'bold');  
   $("#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. = String.fromCharCode(id.charCodeAt() + 1) //Eg of string manipulation
12.ID of btn in its event handler:  var id =;
13.Show/hide panel on clk: TxtBoxId = + "Text";$('#' + TxtBoxId).toggle('slow, linear'); 

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.



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 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.,name,specs,replace)

From <>

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

 var myclients = new Array();
                var i = 0;
                while (i < data.length) {
                    myclients[i] = JSON.parse(data[i]);// data[i] eg: ‘{CollegeName:10, TeamName:”test”}’
                $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(/(?:^|:|,)(?:\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’}


var b = JSON.stringify(a)




var c = b








var d = JSON.parse(c)



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



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

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(/(?:^|:|,)(?:\s*\[)+/g''))) {

                        type: "PUT",
                        url: "http://localhost/..." + querystring,
                        data: { "": jsonData },
                        success: function(result) {

                } 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


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

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

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

JQuery ajax sample:


                    type: “DELETE”,

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

                    success: function(result) {




                     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

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 :
<table width="100%" style="text-aligncenterpositionrelativemarginautomargin-top20px;" class="table table-striped table-bordered table-condensed">
            <tr style="text-aligncenter">
                <th id="ClientList">Game Clients</th>
                <th id="AddClients">Add Clients</th>
                <td width="50%" align="center">
                        class="gridStyle" ng-grid="gridOptions" style="widthinheritheightinheritmin-height500pxmin-width750px;">

Bootstrap form sample code (generated using



                        <!– 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=””>



7.       Note that don’t use the form submit button from
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>




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.