Friday, June 20, 2014

Avoiding CORS on localhost testing via Simple Node.js Proxy Server

What Is CORS Anyway?

Before I get deeper into this topic, I just want to tell you a bit about CORS. CORS an abbreviation of "Cross Origin Resource Sharing", and it is described in this Wikipedia Article.  To make a short summary of this issue, basically, what it means is that there is a security mechanism in just about every modern browser that prevent you to perform AJAX requests from a different server than where your original content came from.

For example, a typical tutorial lesson you get from books may require that you have a simple web server running on Node.js (really easy and cool) then a separate database server that's serving up JSON data (for example, via a Deployed service), you would do something like http://localhost:5000 for your web contents and then http://localhost:5500 for JSON data server. That triggers CORS.

Of course, if you ask most experts, they will say, the answer is easy. They will say just enable CORS on the server side. But it is not that simple. This is a blog about answers that experts do not know how to answer after all.

The reason I am writing this article is because I spent a couple of days to explore different ways of resolving this issue when I was writing some local development and testing environment to learn Angular.js

Because of a very specific way Angular.js performs the HTTP Get and Post the JSON data, you will find it difficult to get around CORS issue. There is even an extension in Chrome to allow CORS in Chrome but even with it, the POST part of the equation does not work for me. In my case, even if I (thought) modified the header to do;

Access-Control-Allow-Origin *
It still did not give me the result I wanted. I even read that on Firefox, a * is not even permitted, and that a specific host be specified. Pretty tricky if you want to test various browsers too! (*I even implemented a version of Microsft IIS site with web.config edited to allow CORS with no avail!)

It is also even worse when dealing with a localhost than any other hosts to get around CORS.

The Proxy Based Solution

In my situation, what ended up working the best is to completely avoid CORS altogether and make it look as if the database service is coming from the same server. And as a bonus of using Node.js it is quite easy to implement it.

It is basically the use of proxy-middleware (e.g. npm install proxy-middleware) that solved this. In this case, all of my test implementation files are stored under ./angularjs folder, so for example, http://localhost:5000/app.html will pull the file from ./angularjs/app.html

I then created a Deployd server at port 5500 (i.e., http://loclhost:5500) and I wanted my server to proxy all of these requests to that when an AJAX request is made to http://localhost:5000/db  So this means that when I was originally doing http://localhsot:5500/products to get the Products JSON data, I will request http://localhost:5000/db/products

var connect = require('connect')
    , url = require('url')
    , proxy = require('proxy-middleware')
var app = connect();
var proxyFunc = proxy(url.parse('http://localhost:5500'));
app.use('/db', proxyFunc);

Stupid Side Note:

Actually, when I tried this the first time, it did not work, the POST failed, because I had some leftover modifications like this in my code

      app.config(['$httpProvider', function ($httpProvider) {
            //Reset headers to avoid OPTIONS request (aka preflight)
            $httpProvider.defaults.headers.common = {};
            $ = {};
            $httpProvider.defaults.headers.put = {};
            $httpProvider.defaults.headers.patch = {};

Be sure to back out any attempts you've done to fix the issue.  It should just work with a bare-bone POST call of Angular.js HTTP provider!

Wednesday, June 18, 2014

JavaScript for C# Programmers: Enumerating Properties

JavaScript Tips for C# Programmers

If you are from the C# (C or C++ too) world, mainly and you are planning to dive into more of "current" way of the JavaScript, you'd run into situations where "I can do this in C#" but why not in JavaScript, or what is going on here, it's not possible in C#.  Here are some notes I was taking as I was learning to apply to my situations. I think you are likely looking for the same answers.
Two Key Concepts in Understanding JavaScript Object

As I got up to speed with JavaScript coming from years of C# only programming, it dawned on me that there are two key concepts that really helps to un-do your C#, C++ minds.  The first one is the dynamic aspect of JavaScript, and also the rampant use of in-line function declarations.

It is Dynamic!

The most important thing to be aware of as a C# or C++ programmer is that the language is dynamic. This is very important in understanding the source codes.

For example, you'd be often confused reading lines of code and suddenly you run into a new property like .address in the example below,

myInfo.address = "1234 Main St.";

You could be wondering where is this .address come from? Where is it declared?

The key to understanding this is that the address member was just added now. There is no requirement in JavaScript to declare anything. You just build your object as you go. This approach is so different that even if you understood it first in a textbook, it will catch you off-guard. We are so fixated in the declaration part of it, it is hard to get rid of that thought. (Note there is a type of declaration, in JavaScript but I am not getting into that now.)

The easiest way to understand this in another way is that if you have used C# Dictionary<> then any JavaScript object is the equivalent of  MyObject.

Add("address", "1234 Main St."); In other words, JavaScript objects are nothing but key value pairs of name and objects.
Rampant Use of Function "Pointers or Delegates"

This is also another difficult part to undo your minds.

A JavaScript object can be a function and JavaScript programmer uses almost exclusively of this. And to confuse the matter even more, many of these functions are anonymous functions. And because you can do that a function are defined usually in a context of a function call! This is so widely used that without understanding this, you would not understand the most JavaScript code these days

var  myFunc = function(x) { return x = x + 1; }

is an example of anonymous function that's assigned to a pointer variable (so to speak) myFunc.

So later on the code you can do y = myFunc(2);

I don't like the term "anonymous" function as everything has to have some reference point. In fact, it does have a name in my example, which is myFunc. So whenever you hear about anonymous function, think of it as a function that's assigned to a variable which is like a function pointer in C or C++, or a delegate in C#.

This approach is used very commonly in callbacks.

myCallback(function(data) { ... });

This is same as

var myFunc = function(x) { return x = x + 1; };

But it is done "in-line" in the calling parameters, which is especially odd looking with the C#, C++ mindset. But if you accept the fact that you can write a function as a parameter to a call, then it will start to sink in.

How To Access A Property That's All in Numeric String.

Given this is a very esoteric situation, it also illustrates a point that you can simply access any member of an object using the object['memberName'] notation.

Consider this situation (this is from Medical Imaging, DICOM protocol JSON obeject except that I have added 'patientName" to demonstrate the following example.)

'patientName' : { 'vr' : 'PN', 'Values' : ['Smith^John'] }

  '00100010' : { 'vr' : 'PN', 'Values' : ['Smith^John'] },

  '00100020  : { 'vr' : 'LO', 'Values' : ['123456'] }

The above is equivalent of the C# code like this.

public class myData
   public patientName = new DataElement();
   public  DataElement 00100010 = new DataElement();
   public  DataElement 00100020 = new DataElement();

Of course, this is not an acceptable syntax in C#, but it is in JavaScript it is possible to have something like this (and it is a part of the DICOM Web standard.

The patientName part is easy to get to just say something like myDataInstance.patientName, but if you try to do myData.00100010  it won't accept that (neither in C# nor in JavaScript actually).

Fortunate in JavaScript the objects are accessible as key value pairs and so it is possible to say theData['00100010'] to get to its content.

How About Finding All Its Properties?

You can iterate through

for (var prtop in heData) {
     var name = prop;
     var val = theData[prop];

What is the === Stuff?

Remember, just this important point. JavaScript auto-converts types when doing an "==" comparison, so you can compare a string that just contains digits against an actual number and come out to be equal. === prevents that from happening.

To be continued...

CSS for C# and C++ Programmers

CSS (Cascading StylSheet) is another area in web programming that is rather confusing if you come from pure C# or C++ world, because the notation look somewhat like a declaration in these languages. If you are reading on and if I write "in C#" that I generally mean in C# or C++.

Like me, I am sure you have been using the CSS without completely understanding any of these, but these simple descriptions will make it all clear once and for all. So here are some tips to "un-do" our mindset;

Differences Between .myStyle, #myStyle and Barebone Symbol Form like a "p"?

  • If it starts with a # , like #myid, then it applies to the element with the id attribute included like <dive id="myid">  And no it is not a comment.
  • If it starts with neither of these then it mostly refers to "officially out of the box html" element tags like or <p> type items.
  • If it starts with a period like .mystyle } then it is a class specifier. This means that somewhere down the line in the HTML code you see something like then that's where this style applies.  Note therefore it does not mean anything like "this" in C#.

    This has a larger implication, though, as you might see something like "p. mystyle" that means it applies only to when there is
     This is thus not a member type stuff, but more like narrowing the scope of where it applies.

Cascading or Inheritance

We tend to think everything in terms of  Object Orientation, so we are all used to inheritance and as the name implies the cascading part of the style sheet allows inheritance. So how would that be implemented?

The answer is that the inheritance is basically automatic. In other words, if somewhere early on in the html content stream or even in some JavaScript code the style was changed, then you define something more to it, then whatever you defined newly will be either overridden (if the same attribute was specified) or added to that point. 

Listing More than One Names in Style is Not Inheritance Declaration

You sometimes run into a style declaration that lists a bunch of style names. It looks like a bit like subclassing a class or defining interfaces, but it just simply a way to aggregate declarations of several styles.

.style1, style2, style3{  ... }

It simply means all 3 styles use the same attributes (to start with). This might be useful to make all these 3 styles to have the same font then you will later customize each style.

Apparently There is No Easy Way To Clear or Reset a Style

We may want to clear everything in style, but there appears to be no simple way to do it. If you search for "CSS Reset" there are many ways that let you do it. But there is no real official way in wide use (as of June 2014 at least), and keep in mind, even if that's available in the new CSS standard, you are dealing with millions of people running just about any version of web browsers ever made.

So the surest way is to override style elements to laboriously redefine any aspects of it. 

Including Stylesheets

<link rel="stylehseet" type "text/css" href="css/style.css">

Yes, this is the include statement for the CSS. In most web pages, link is used pretty much only for stylesheets. Note that <script> uses standard src= element, so this is pretty much one "odd-ball". Just remember it that way.

    Sunday, June 08, 2014

    Understanding the c# Attributes


    You see other class declarations in C# using attributes, but you do not quite understand what it does.


    The following is neither a complete nor perfect example of it, but it does demonstrate some few simple points about the C# attributes.

    The most important things for you to know about this to me are the following;
    • Attributes, especially the custom attributes you define, goes usually with the Type (i.e., typeof()) , and not with the instance or implementation of a class. This distinction is one of the key in importances in understanding the attributes.
    • As such, it is a way to associate additional information given to the class. Why this could be important is that, for example, the base class can pull the attribute parameters on the behalf of derived classes. You could do this in any number of ways, but this is just another way, and obviously there are more complex use-cases.
    • In the example below I have defined the base base class of SurfBerak which can be derived into any surf break in the world.
    • I have defined two example breaks, one in HalfMoonBay and one in SCW (Santa Cruz West Side). Do note that I do not have anything in these sub-classes, nevertheless if you run the console app example, it will show you proper location and the bottom type just as if I have created a constructor in each class and initialized them with the break name and the bttom type. This is because the break name and the bottom types are specified in the attribute.

      In this case I have written my baseclass, but what if you are using someone else's base (for example a lot of Microsoft's classes) with an ability to specify attributes like I have, then you see a significant potential. You could look at this way; you have just customized the base class with some simple parameters in the attribute.
    • You might be wondering why the break name and the bottom type are specified a bit differently. The break name field is in the constructor parameter of the SurfAttribute class. Microsoft calls this a "positional" parameter. Then there are named parameters. Named parameters are just members of the SurfAttribute class each with a get and a set. Unlike your regular C# class, you should not make the set path as a private. It will not work.
    • You would also notice that in each subclass declaration I say things like [Surf("Hal Moon Bay", bottom = "Sand")]with the keyword of Surf. This is another convention. You can omit the word "Attribute" altogether. 

    using System;
    using System.Linq;

    namespace AttributeCheck
        internal class Program
            private static void Main()
                var br = new SurfBreakHMB();
                Console.WriteLine("I have surfed at {0}, Bottom {1}", br.BreakName, br.bottom);
                var br2 = new SurfBreakSCW();
                Console.WriteLine("I have surfed at {0}, Bottom {1}", br2.BreakName, br2.bottom);

        public class SurfAttribute : Attribute
            public SurfAttribute(string breakName)
                this.breakName = breakName;

            public string breakName { get; set; }
            public string bottom { get; set; } // note that set cannot be private

        public class SurfBreak
            public SurfBreak()
                Type t = GetType();
                object[] ci = t.GetCustomAttributes(true);
                foreach (SurfAttribute at in ci.Where(i =&gt; i.GetType() == typeof (SurfAttribute)).Cast())
                 BreakN   ame = .breakNatame;
                 bot   tom = at.bottom;

            public string BreakName { get; private set; }
            public string bottom { get; private set; }

        [Surf("Hal Moon Bay", bottom = "Sand")]
        public class SurfBreakHMB : SurfBreak

        [Surf("Santa Cruz, West Side", bottom = "Reef")]
        public class SurfBreakSCW : SurfBreak

    Sunday, June 01, 2014

    Moto X (Android 4.4.2) Bluethooth Headset Stutter then Other Party Cannot Hear for a Few Seconds


    You have a Bluetooth headset and when you begin a phone conversation, it stutters (click... click... click... sound heard) then a silence for a few seconds, then the phone conversation gets interrupted for a few seconds then resumes.

    Possible Root Cause (Inconclusive):

    It appears that this happens when my phone tries to auto-connect to either the Xfinity Wifi or AT&T hotspot as you drive by the area where the access point is available.

    Possible Fix or Workaround:

    • Try disabling the WiFi altogether. If this fixes it, then you may have the same problem I have experienced.
    • If the above situation applies to you, then "forget" the Xfinity Wifi connection from your Wifi setup. Also, you may have an Auto Connect with the AT&T Wifi as well. These are in the Advanced part of the Wifi setup. I would first try to disable auto-notification and auto-connection features and try again.

    Side Notes:

    This happens to me when I am driving in my neighborhood; just when I am driving away from home (I usually begin the day's calls when I leave home). This does not happen when I am driving in a less populated area along the way. I recalled using an Xfinity (or Cable Wifi) hotspot recently now that Xfinity is enabling public hotspots to many home subscribers. I have figured that this could be causing the problem as I pass certain neighborhood areas this happen just as if some homes are generating interfering Bluetooth signal.

    I drove around with my wife's cell phone making a call to it and mine and tested to see if the stuttering happens and after the above fix made the problem appears to be fixed.