If you work in javascript, these results shouldn’t be surprising

photo credit: /doh via photopin (license)
photo credit: /doh via photopin (license)

Hey Folks,

Javascript has some weird stuff built into it and sometimes when used in conjunction with other languages, it is easier to forget the corner cases that can come with javascript coding.

Here I compile the list checks, that every developer working in javascript should know, so that there are no accidental bugs and also sometimes these can be use to our advantage

Equal operator comparison

Double Equals

Comparison Result
null == null true
null == undefined true
null == 0 false
null == ” (empty string) false
null == NaN false
null == ‘2’ false
null == 2 false
undefined == null true
undefined == undefined true
undefined == 0 false
undefined == ” (empty string) false
undefined == NaN false
undefined == ‘2’ false
undefined == 2 false
0 == null false
0 == undefined false
0 == 0 true
0 == ” (empty string) true
0 == NaN false
0 == ‘2’ false
0 == 2 false
” (empty string) == null false
” (empty string) == undefined false
” (empty string) == 0 true
” (empty string) == ” (empty string) true
” (empty string) == NaN false
” (empty string) == ‘2’ false
” (empty string) == 2 false
NaN == null false
NaN == undefined false
NaN == 0 false
NaN == ” (empty string) false
NaN == NaN false
NaN == ‘2’ false
NaN == 2 false
‘2’ == null false
‘2’ == undefined false
‘2’ == 0 false
‘2’ == ” (empty string) false
‘2’ == NaN false
‘2’ == ‘2’ true
‘2’ == 2 true
2 == null false
2 == undefined false
2 == 0 false
2 == ” (empty string) false
2 == NaN false
2 == ‘2’ true
2 == 2 true

Double equals is not the same as triple equals when it comes to javascript. Notice that some things are unexpectedly true example 0 == “” is true when only compared with double equals vs its false when compared with triple equals. Double equals can somehow be helpful when you want to check if the value is either null or undefined you can quickly just do if(val == null) instead of if(val == null || val == undefined). Also notice that double equals does not check for the data type behind the comparator, example 2 == ‘2’ is true but not true in triple equals.

Triple Equals

Comparison Result
null === null true
null === undefined false
null === 0 false
null === ” (empty string) false
null === NaN false
null === ‘2’ false
null === 2 false
undefined === null false
undefined === undefined true
undefined === 0 false
undefined === ” (empty string) false
undefined === NaN false
undefined === ‘2’ false
undefined === 2 false
0 === null false
0 === undefined false
0 === 0 true
0 === ” (empty string) false
0 === NaN false
0 === ‘2’ false
0 === 2 false
” (empty string) === null false
” (empty string) === undefined false
” (empty string) === 0 false
” (empty string) === ” (empty string) true
” (empty string) === NaN false
” (empty string) === ‘2’ false
” (empty string) === 2 false
NaN === null false
NaN === undefined false
NaN === 0 false
NaN === ” (empty string) false
NaN === NaN false
NaN === ‘2’ false
NaN === 2 false
‘2’ === null false
‘2’ === undefined false
‘2’ === 0 false
‘2’ === ” (empty string) false
‘2’ === NaN false
‘2’ === ‘2’ true
‘2’ === 2 false
2 === null false
2 === undefined false
2 === 0 false
2 === ” (empty string) false
2 === NaN false
2 === ‘2’ false
2 === 2 true

Triple equals is much tighter comparison in javascript, it also checks the data type example see that 2 === ‘2’ is false while its true in double equals


Or (||) operator comparison

Comparison Result
null || null null
null || undefined undefined
null || 0 0
null || ” (empty string) ” (empty string)
null || NaN NaN
null || ‘2’ 2
null || 2 2
undefined || null null
undefined || undefined undefined
undefined || 0 0
undefined || ” (empty string) ” (empty string)
undefined || NaN NaN
undefined || ‘2’ 2
undefined || 2 2
0 || null null
0 || undefined undefined
0 || 0 0
0 || ” (empty string) ” (empty string)
0 || NaN NaN
0 || ‘2’ 2
0 || 2 2
” (empty string) || null null
” (empty string) || undefined undefined
” (empty string) || 0 0
” (empty string) || ” (empty string) ” (empty string)
” (empty string) || NaN NaN
” (empty string) || ‘2’ 2
” (empty string) || 2 2
NaN || null null
NaN || undefined undefined
NaN || 0 0
NaN || ” (empty string) ” (empty string)
NaN || NaN NaN
NaN || ‘2’ ‘2’
NaN || 2 2
‘2’ || null ‘2’
‘2’ || undefined ‘2’
‘2’ || 0 ‘2’
‘2’ || ” (empty string) ‘2’
‘2’ || NaN ‘2’
‘2’ || ‘2’ ‘2’
‘2’ || 2 ‘2’
2 || null 2
2 || undefined 2
2 || 0 2
2 || ” (empty string) 2
2 || NaN 2
2 || ‘2’ 2
2 || 2 2

This works like standard || or operator, if the value of the first comparator does not equals to true it will select the other value. See section truthy value for which values return false when asked for boolean value.

Truthy value

Comparision Result
if ( null ) false
if ( undefined ) false
if ( 0 ) false
if ( ” (empty string) ) false
if ( NaN ) false
if ( ‘2’ ) true
if ( 2 ) true

Hopefully this can help someone have a reference check on what javascript does on == , === and || operators.

Let me know in comments..

  PS: I originally created this post in jsfiddle here (http://jsfiddle.net/bsurela/13gdvom5/)

Generate Random Colors

random colors
Hello Folks,

This post is just dedicated to check out http://bhavinsurela.com/color-generator/, a simple random color generation that i created. This is no rocket science but its fun to drag and drop colors around each other and to see them create different colors.

It works best in Chrome and uses drag and drop of HTML5 and also uses local storage. This is just a gig and some couple of hours of work, but I still hope it will be used somewhere.

Talk to you soon!

Naive way of overriding console.log

Howdy,

Happy new year folks. I hope you had a fantastic year and plan to have a great 2015.

I am going to start 2015 with a simple naive trick. I am sure there are other good ways and things out in the wild to achieve similar results.

I was visiting a site for holiday shopping and I notice tons and tons of console logs. I assumed that the site was in debugging mode and had lot of console prints. It got me thinking that what would be the easiest way to get rid of those console logs in production while still keep them in debugging/developing mode. Of course assuming that they have no prior built-in switches for that.

I opened up my fiddle and here is what I came with, It works well and pretty easy to use. Its a simple logger. It uses domain name array which is the array of all the domains in which the console.log should be hidden (example, production domain). It has a force switch which allows you to still print logs in production (in case you are working like me where your end users are in the same room). This is a bare-bone structure to give you the idea – it can obviously be tweaked according to one’s need.

Here is the embedded fiddle

With this, all the console log disappear from production while still appear in everyones local.
Hope this helps someone.

Happy Coding.

Setup SingalR self-host in SSL

Hi Guys,

There has been a lot of buzz about singalR lately and If you havent checked it out yet, singalR is a fantastic realtime communication system, you should give it a go.

For friends who have played around with singalR and tried singalR self host and want to host in SSL, read on.

Setting up singalR in SSL is relatively very easy but not straight forward, I did not find it in documentation that this is the way to do it.
So here is my own.

Steps to create and host a signalR package in SSL

1)Get singalR self-host running, for help and quick start install nuget owin package

Install-Package Microsoft.Owin.Hosting -pre
Install-Package Microsoft.Owin.Host.HttpListener -pre
Install-Package Microsoft.AspNet.SignalR.Owin

Lets set up singalR on http://localhost:8082

static void Main(string[] args)
        {
            string url = "http://localhost:8082";
            using (WebApplication.Start<Startup>(url))
            {
                Console.WriteLine("Server started URL "+url);
                Console.ReadLine();
            }
        }

 

    class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // to turn on cross domain and other stuff
            var config = new HubConfiguration { EnableCrossDomain = true, EnableJavaScriptProxies = true, EnableDetailedErrors = true };
            app.MapHubs(config);
        }
    }

 

After successfully doing it you can navigate to http://localhost:8082/singalr/hubs and you will see your dynamically generated hubs file.

so at the moment we have it running on localhost on *non* SSL environment.

 

To run it in SSL, you need an SSL certificate. Two things to note here

1) SSL is port 443 or your ip address(localhost)

2) SSL needs a certificate (I am not going into detail about creating an SSL certificate but you can find it here)

But wait, we have hosted our singalR at socket address= localhost:8082, How is it going to map at port 443 then?

It wont. When you set up an SSL it will map to socket address = localhost:443 (because of point 1)

 

To make it work you need a SSL certificate (a self signed will do) for your localhost and a *unique* url to host singalR

so after creating a SSL certificate i have changed the above mentioned code to

static void Main(string[] args)
        {
            string url = "https://localhost/server1/";
            using (WebApplication.Start<Startup>(url))
            {
                Console.WriteLine("Server started URL "+url);
                Console.ReadLine();
            }
        }

now if you navigate to https://localhost/server1/singalr/hubs you will see a dynamically generated file.

What does this tell me?

It tells me that I have hosted my signalr on https://localhost:443/server1/

But I have not enabled any port sharing, how does this work?

IIS automatically enables port sharing, and so does singalR. You can host as many server on SSL on a singal ip address/domain name

Note: if you have a domain name for your localhost you can use that too for example, https://mydomainname.com/server1/singalr/hubs

You can point your localhost/127.0.0.1/loopback address to a domain name in your host file.

 

Simple and quick, Hopefully this will help someone start easy.

Silverlight Event Calendar with MVC 3

I love it when two development technologies shake hands with each other to make a composite product. I have been playing around with integrating one technology with another lately and today’s blog is dedicated to integrate Silverlight control [Cal…

I love it when two development technologies shake hands with each other to make a composite product. I have been playing around with integrating one technology with another lately and today’s blog is dedicated to integrate Silverlight control [Calendar] in MVC 3. For those who are new to .Net development technologies, I suggest you have a look at Silverlight and MVC

It is not always the case when you are bound to use Silverlight in MVC 3 solution especially a Calendar control, you can achieve the similar functionality with tools like JQuery, Telerik Calendar Control and many more. However Integrating Silverlight in MVC 3 is not as easy like the above mentioned tools. I ran into this scenario a while back where I was supposed to have an event calendar control in my MVC 2 project and I decided to take a higher route of implementing this by Silverlight just to learn how to integrate it. It was not easy for me to do that the first time but in the end I have to admit it was slick. :)  I will try to give a demo on how to integrate Silverlight Control in MVC 3 razor view. Also you can add other silverlight control just the same way. We will also be using JSON to communicate between Silverlight and MVC 3.

Lets Begin….

 First of all 

1) Add a Silverlight project in to your MVC 3 Project (Select Defaults, let it create a Test page) 

2) In your Silverlight project Add Reference to   System.ServiceModel.Web, System.Runtime.Serialization

After all that your solution should look something like this.. 

 

Now let’s edit XAML in Silverlight and put a calendar control and textblock in it.

 

34211421-soln

I edited it with some basic design properties and here is how it looks..

34211491-xamldesign

 

Now let’s create MVC View which will host this Silverlight calendar. To do that Just create a view and locate a file called “YourSilverlightAppNameTestPage.aspx” in my case it is CalendarTestPage.aspx, Right Click ->View Code and copy the script and html  and paste it into your MVC View.

Do not forget to remove Head and Body tags from your MVC View after pasting the content.

Now set the path of your zap file matching inside your ClientBin folder, or simply use the url to that. Here is how it looks in my case.

34211741-view

 

Notice I have all the height/width value in “px”. Sometimes some browser does not like % with Silverlight and they will not just display the content in that case so try to use px with Silverlight as much as possible.

Put a method to display view in your controller. And run your web project to see if you can see a Silverlight calendar. You should be able to see something like this….

 

34211846-initialview

 

If you cannot see something like this then, check your source path in your view, That is mostly the culprit, Clear your browser cache and try it in different browsers..

Check above steps if you missed any if you still cannot see it.

Ok so now you have a Silverlight calendar in MVC but we didn’t do all this trouble just to display a calendar we want to pass in some data to this calendar and make is a traditional event calendar.. So we add a model in our MVC now.

I just created a CalendarModel like this to show the demo, 

34211964-Model

 

So as I said, you will have a proper db calls to fetch event data or something, in this example a constructor call is enough to have some fake data to test our calendar control… now, In your Controller add a method which fetches this data from the model.. Something like this..

34212005-controller

 

What we did here is we have created a bridge for our Silverlight app to communicate with our mvc and fetch the data for its internal processing..

Now lets code in Silverlight app to get data from this bridge…For this copy the Model you created and paste it into your MainPage.Xaml.cs under your namespace, Why? Because we are going to juse DataContractJsonSerializer which will need the datatype to model to convert json into some sort of datatype.

One can say that why not add a reference to our project and use the model directly, well you cannot add reference of your projects which are not built against Silverlight runtime, so that wont work. 

Anyways.. after you added that into your silverlight, add this code to your file..

34212341-xamlcs

 

Ok so you can see couple of ugly red arrows right, lol, they are ugly to get your attention. So you need System.Runtime.Serialization.Json for DataContractJsonSerializer and this is why we added two references at the begining of our project.

You also need member variable of CalendarModel to store and compare the data on SelectedDateChange event.. We will store the data we get from MVC in this member variable, this is why we need to paste our model in Silverlight project too, so we can create an object of that class which can hold the data that came as Json from our special bridge we made.. 

Notice in Page_Loaded we have created a web client object which will read asynchronously from the “Event” method in our controller [our bridge.. :) ] Also notice that for demo purposes i have hard coded the url [after hard coding the port I am running my web app]

If you deploy it to IIS later on, do not forget to change it to your actual url.

And now finally we have mvc_OpenReadCompleted method, which actually fetches the data from the Json and convert it into our CalendarModel..

Now to make an Event Calendar I have to add these dates to my calendar control hence.. loop going through adding each one in the calendar control…

Now I have not described why i have used member variable loadCompleted in this class, Well here is why, SelectedDateChanged method is called when the calendar control is rendered, which is the same method we are going to use later, to display the details of Meeting.  That variable is a mechanism to differentiate between when this method is called by client (the person using the web page) or by our application while loading the calendar control..

And Finally we just add a SelectedDatesChanged method..to complete the task we started.. 

Here is how it looks.

 

34212707-dateschanged

We are just displaying the details i.e. MeetingTime, MeetingAgenda and Meeting Name here when selected date matches the one that are passed by our MVC. You can do all your complicated stuff here.

That’s it, Finally we will be able to see Silverlight event calendar..

Here is the look

 

34212786-event1
34212790-event3
34212789-event2

Silverlight is known for its rich media, I will suggest you that if you ever use this, use everything in Silverlight to make is as much pretty as possible so that your efforts look worth, I did it once and I can say no JQuery calendar could look that slick.. 

And we are done…

You now have a decent Silverlight Event Calendar in your MVC 3 project….

I still strongly suggest using JQuery/Telerik Controls for Calendar control, but I understand sometimes things have to be done some specific way and it might be helpful if we have a knowledge of how to integrate different Microsoft technologies together. 

Hope you will stick around… Happy coding..

later…

Highlighting current page in MVC 3 – Slick Trick.

Hi Everyone, Well I was on a development of one of the websites lately and I was using MVC 3 to create it. I have always liked when the menu bar highlights the current page. It is very easy to do in a website without master page which have separat…

Hi Everyone,

Well I was on a development of one of the websites lately and I was using MVC 3 to create it. I have always liked when the menu bar highlights the current page. It is very easy to do in a website without master page which have separate body tag for each page, Only CSS is required for that, but when it comes to MVC 3 which has a layout page and only one body tag, the CSS trick just wont work.

There has been lots of blogs and discussions for doing this but I noticed they all need a lot of code or scripts to do that. I believe that doing something like this should not take more than 5-10 lines of code and should be mostly CSS. I was able to do it with this trick, I think it will be fairly a time saver for new MVC developers..

We want to achieve something like this:

34120847-menuhome
34120846-menuabout

Here is how my Controller looks like. Notice that I have added keys to ViewBag ie. ViewBag.CurrentPage and both Home and About methods initialize it to “home” and “about”.

We will use this to identify current page on our razor code. 

 

34117774-controller

 

This is how my body tag looks like

34120058-body

I am giving body a dynamic id, that id will be my ViewBag.CurrentPage value which means my body will have different id when i navigate to different page say Home or About.

and this is how my menu items looks like, nothing much special about it, just adding id attribute and value, Home link has id “home” and About link has id “about”

34120330-layout

and finally the CSS

34120381-css

So now we have something equivalent of having multiple unique body id at one time for the browser. Whenever the anchor tag id and body tag id matches, it will override the current stylesheet with our defined new one [in the above picture]

 

So Simple isn’t it. Saves you a lot of coding as compared to other blog/discussions I have seen.

Please note that you have to take special care when you are doing some scripts that use your body tag id.

Other than that, you are all set to explore your style sheets skills to make a super cool menu bar.

Stay tuned we will be having more MVC 3 stuff comming up soon.

Cheers!