Friday, July 17, 2015

Javascript Prototypes and Prototype Pattern


Reason why i am blogging about this because i seriously like to share how i got my confusion removed regarding JavaScript Prototypes, i used prototypes for last 3 years just because someone has used it and with a confusion regarding its basics i was just implementing it, this is the case with many of us and this is one of the most confusing topic until unless you don't explore it practically.

I will show you how i actually got clear about prototype and finally i love these and consider its pattern as the most handy and important when comes to developing APPS.

Note:- I am using Chrome Developer tools console tab for demonstrations.

Prototype, as per the oxford dictionary a prototype is  :-

A first, typical or preliminary model of something, especially a machine, from which other forms are developed or copied.

So in simple words prototype is a model to create copies out of, and if i relate it at this point with JavaScript and my programming knowledge so it must be my functional blueprints to create objects out of, which is partially true but it has more functionality, now lets see what popular article says about prototype as single lines definitions:-
  1. A prototype is an object from which other objects inherit properties.
  2. Every JavaScript object has a prototype. The prototype is also an object.
  3. All JavaScript objects inherit their properties and methods from their prototype.
So keeping above three definitions in mind i thought to explore it Chrome browser console and see the practicality of definitions. But first for folks  who does not know what a JavaScript object is!
 here is a quick information:-

JavaScript Object (Layman Language {key:value} )
A JavaScript object is really just an unordered collection of key:value pairs, and you create  key:value pairs separated by commas and packed in Mustaches(Curly Braces):-

var Student = {Name:'John Doe', ID:1} // this is a container with properties.

A JavaScript object contains properties as shown above and can also contain methods/functions too :-

var Student = {Name:'John Doe', ID:1,SayHi:function(){alert('hey By ' + this.Name)}}

And to access property one has to use:- Student.Name or Student['Name']

To access methods:-

Analyze JavaScript Object in Chrome console window for prototype

Open Chrome, default will be, and just press F12 open console (Open Console window, i have put it in the source tab)
  1. There are many ways to create a simple blank object:-

  2. As you can see above i created ankur1,ankur2 and ankur object by different ways.
  3. Now when i checked my object ankur i can see some method which says ankur.isPrototypeOf () which raised my eye brows and immediately i thought using this method i can actually verify and relate the second definition which says every Object has a prototype.
Now if every object has prototype which is an object then there ankur.prototype should be that property/object.
Thinking the same when i checked in my browser console i got surprised to see that ankur.prototype is undefined:-

so is the definition wrong or confusing? Actually it turned out that it was  confusing not wrong:-

The true prototype of an object is held by the internal [[Prototype]] property. ECMA 5 introduces the standard accessor Object.getPrototypeOf(object) which to-date is implemented in Firefox, Safari, Chrome and IE9. In addition all browsers except IE support the non-standard accessor __proto__

And every object is created using with a Constructor initiation so we can access prototype object using prototype property of constructor too(this works in every browser):-

Now this gave me a bigger clarification on the definition of prototype:-

Every JavaScript object has a prototype. The prototype is also an object.

 Lets move forward and analyze the use of prototypes with its two other significant definition:-

  • A prototype is an object from which other objects inherit properties.
  • All JavaScript objects inherit their properties and methods from their prototype.

To show exactly what these two definition mean, we need first to know something very unique to functions in javscript:-

Every function in javscript has a property called prototype, and we use functions to create objects like i did above when used function Object() with new to create ankur1, just see this :-

Now as shown in the console above, we created a new function Myfunction and it does have a prototype Object which is the same when we create a new object as "new Myfunction()" and try to get the Prototype of that Object.

This prototype property does have significance when  functions are used as constructors to construct a Javascript Object.
A function’s prototype property is the object that will be assigned as the prototype to all instances created when this function is used as a constructor.

There is chain in javascript Objects, every Objects inherits from Object.prototype which sits at the top of the Chain.

Moving forward, i saw many examples on net where people have defined one level of inheritance using Protoypes, you can find multiple blogs which talks about single level of inheritance like this example:-

var humanConstructor = function human(name) { this.Name = name };
var Male = new humanConstructor("Man");
var Female = new humanConstructor("woman");
//later on i added this..
humanConstructor.prototype.From = function () {
    this.Name === "Man" ? alert("I am from Mars") : alert("I am from Venus");

Male.From();//Output:"I am from Mars"
Female.From();//Output: "I am from Venus"

The above example is very nice and simple one level inheritance example of prototypes definition mentioned above.
I just added From later on and automatically it got inherited by my objects.

Using this way i can customize my initial functions(constructors) and add Methods to prototype Object later on, Automatically all my Objects constructed using initial function will get new methods.
But it stores the reference of prototype not the value.

Till this it was fine, but later i thought:-
How can i create a Object from Male(from above example)  example Boy, and test multilevel inheritance and Chain behavior. And if i try to do this :-

var Boy = new Male(); //This will give error.

I got error:-

So, after a research i learned about Object.create()

So What does actually Object.create() do?

  • Object.create(proto [, propertiesObject ])

It extends a prototype and also can add properties using propertiesObject parameter.

So this is the way to create multilevel inheritance and define the chain mechanism in prototype.

See the use of Object.create():- here:-

var humanConstructor = function human(name) { this.Name = name };

var Male = new humanConstructor("Man");
var Female = new humanConstructor("woman");

//later on i added this..
humanConstructor.prototype.From = function () {
    this.Name === "Man" ? alert("I am from Mars") : alert("I am from Venus");

Male.About = "I am the man";
//Object.getPrototypeOf(Boy).About = "My Name is George, and i am  a Male";
var Boy = Object.create(Male);
alert(Boy.About);//I am the Man

One practical use of prototypes:-
This was where i recently used prototypes, i created a single page app that is meant to work on every browser, it was required to work even in IE8, there is a function in latest browsers called  "toISOString()", this was not working in IE8 and some other versions of browsers, but i did used it excessively, so to overcome the issue i used prototypes and created this :-

 if (!Date.prototype.toISOString) {
        (function () {
            function pad(number) {
                var r = String(number);
                //it takes data type in consideration...
                if (r.length === 1) {

                    r = '0' + r;
                return r;


            //here in this case of prototype pattern, this is the object/datatype on which prototype is applied.
            Date.prototype.toISOString = function () {

                return this.getUTCFullYear()
                   + '-' + pad(this.getUTCMonth() + 1)
                   + '-' + pad(this.getUTCDate())
                   + 'T' + pad(this.getUTCHours())
                   + ':' + pad(this.getUTCMinutes())
                   + ':' + pad(this.getUTCSeconds())
                   + '.' + String((this.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5)
                   + 'Z';

Still there is enough left to discuss about JavaScript Prototype but in this blog i wanted to discuss the actual basics of prototypes with practical impressions. Hope it helps.

Tuesday, July 14, 2015

JavaScript Closures (Step 1 for App development)

JavaScript Closures

In this blog i like to write and discuss about the Closures in JavaScript, i am using JavaScript in SharePoint sites from 2007 version, In my first working assignment i was told to premeditate a Site template made using SPServices and Jquery to new SharePoint JavaScript client object model Site back in 2009, It was a Template which enables functionality of  Twitter on SharePoint. But that time i just created and written everything in functions which were added under Global namespace automatically.
And this is normally we do in creating our applications or making some modifications, but with the advancement in client side programming and trend of Single Page applications and many other factors  has introduced design patterns and writing javascript libraries.

To make such libraries one basic important concept is Closure.

A closure is concept made out of anonymous functions and a basic fact in javascript that an anonymous function can be returned from other functions, like it  can also be assigned to a variable

Local variables defined within the containing function are available through the returned anonymous function and this is called Closure.

Now lets see this in a series of examples:-

  1. Basic Closure example:-
    var Maddy = window.Maddy || {};
    Maddy.getStudentName = function Student(id) {
        var students = { '1': 'ankur', '2': 'nelson', '3': 'drew' };
        var getName = function () {
        return getName;

    here we have a namespace Maddy and under that we have a function getStudentName which incorporates an anonymous function accessing local variable students  and retrieving the value of name of student contained in students variable.

    We have just returned the function to the original function.
  2. The inner function is the closure in above example, it has three access chains, it can access its own variable and variables scoped to outer function and also can access Global function, but it can not access arguments directly of outer function, see this example:-

    Look at this example which does not use Closure:-

    Maddy.addArguments = function()
        var sum =0;
        for(var i=0;i<arguments.length;i++)
            sum += Number(arguments[i]);
        return sum;

    It will work perfectly and will give you output of 15.

    Now if you use Closure and try to access arguments it wont work.

    Maddy.addArgumentsWithclosure = function () {
        var sum = 0;
        var doTheSum = function () {
            for (var i = 0; i < arguments.length; i++) {
                sum += Number(arguments[i]);
            return sum;
        return doTheSum;

    it will return '0' in alert and wont work.

    So Closure can access local,outer and global variables but cant work with outer function arguments object.
  3. Closures have access to the outer function’s variable even after the outer function returns, also it stores references to the outer function’s variables;

    example demonstration:-

    Maddy.getValueID = function () {
        var valueId = 101;
        return {
            get_valueId: function () {
                return valueId;
            set_valueId: function (newValue) {
                valueId = newValue;
    var dummyVar = Maddy.getValueID();
    alert(dummyVar.get_valueId()); //output will be 101
    alert(dummyVar.get_valueId()); //output will be 1000
As shown above set_valueId closure still keeps reference to outer function variables even outer functions is allready executed.

Wednesday, July 1, 2015

Configure HostHeaders for SharePoint Web Application in Dev Boxes.


How bad it looks when developing our applications in our dev boxes we use url's like http://xyz-servername:port/

With 2013 to configure apps we need to have some DNS entries created. But traditionally not every developer care to have dns entries created for web applications in dev boxes.

Also learning from my past lessons with different urls in Dev and Production for the simmilar sites, sometimes you have to manually change the urls in infopath forms, workflows to republish the working stuff.

To make things better, here is the way i am sharing on how to configure host header and edit bindings to let the host header work for you without configuring anything on DNS.

We will use Powershell to modify the host file and will also set bindings on IIS to make WebApplication availlable outside the server.

Here are the steps:-

  1. Create a WebApplication (You can extend one if you want to override the existing one).
    I just have created a normal web application with host header "ankurmadaan" and port i used is 80. Note:- i allready have a sharepoint default web application on port 80.
  2. Now we need a root site collection,  I like to keep my site collections in there own database, for me it will be root collection so it will go into default database.

  3. So now if you try to browse, you will be surprise to see that your site does not works, unless you have an entry for http://ankurmadaan in DNS mapped to ip of your server.
  4. Also you will be loop back and Authentication Required pop up will keep coming.
  5. So here is the solution, we will write Powershell Script to make this work:-
  6. First we will write script to get path of hosts file and create a copy of it:-
    #Make backup copy of the Hosts file with today's date 
    $hostsfile = 'C:\Windows\System32\drivers\etc\hosts'
    $date = Get-Date -UFormat "%y%m%d%H%M%S"
    $filecopy = $hostsfile + '.' + $date + '.copy'
    Copy-Item $hostsfile -Destination $filecopy
  7. Above code will create a copy of host file for safe way purpose.
  8. Next we will add entry for "ankurmadaan" in it:-
    Write-host "Adding entry for webapplication" 
    add-content -path $hostsfile -value " `t ankurmadaan"

  9. Last but not the least if not done allready in your server, entry for LoobBackCheck:-
    # Disable the loopback check
     New-ItemProperty HKLM:\System\CurrentControlSet\Control\Lsa -Name "DisableLoopbackCheck" -Value "1" -PropertyType dword

  10. So here it is the working http://ankurmadaan/ :-
  11. If you have multiple webapplications and you want to do this entire step in one go, in that case you can use alternate access mappings, here is the script for it:-

    # Get a list of the AAMs and weed out the duplicates $hostsfile = 'C:\Windows\System32\drivers\etc\hosts' $hosts = Get-SPAlternateURL | ForEach-Object {$_.incomingurl.replace("https://","").replace("http://","")} | where-Object { $_.tostring() -notlike "*:*" } | Select-Object -Unique # Get the contents of the Hosts file $file = Get-Content $hostsfile $file = $file | Out-String # write the AAMs to the hosts file, unless they already exist. $hosts | ForEach-Object { if ($file.contains($_)) {Write-Host "Entry for $_ already exists. Skipping"} else {Write-host "Adding entry for $_" ; add-content -path $hostsfile -value " `t $_ " }}
  12. Now, this will work when you are inside the servers, what will you do to have it accessed by users from outside of the server in your network, like you want to demo it someone, so here is the way to do it:-
  13. Go to IIS  and right click on this Web Application and click on Edit Bindings:-

  14. Add a new entry and specify the port name and add server name(current server) on which you are configuring this, WFE if your dev box has multiple servers:-

  15. Click ok and the last step is to create an extra alternative access mapping. Open Central Admin ->Configure alternate access mappings -> Add Internal URLs -> Change alternate access mapping location to this web application.

  16. Add internal url http://servername:93 what we used in step 14. also select custom for zone
  17. Now browse http://servername:93 , it will open the same site as http://ankurmadaan will open in the server.

    NOTE:- you have to configure hosts file in each of the server connected to your dev box but binding can be done on any WFE to expose the site outside of the server.


Tuesday, September 2, 2014

Hi Folks,
Just today i realized that it has been too long that i have not posted a single post on my Blog, actually i was going through a technical transition stage, in 2014 i am relocated for the time being to U.S to work for a client on certain critical project deliverable. And kind of life a developer has onsite is totally different then what we do at Offshore.
Now these days i am working on Several Technologies apart from Microsoft SharePoint, helped the client in developing some Mobile Apps consuming SharePoint Workflows using Twitter Bootstrap as Front End, SAP HTML5(a.k.a SAPUI5), Microsoft Project Server 2010, Signal R, C++.
And there are many more yet to explore which are on stack for upcoming deliverable like a Google Glass App is in the Queue i have been asked to taste the Flavor of XAMARIN to develop Apps.

Working with so many different technologies creates a genuine requirement to blog about each and everything what you are exploring.

So 2014 will contain blogs not only about SharePoint but also about some random exploration and i am hopeful that whatever i will blog will definitely help others.

Ankur Madaan.

Tuesday, July 2, 2013

Develop Microsoft SharePoint 2013 APPS - Part 1

Yes this is the time I think I should talk about my learning and work with SharePoint 2013 Apps, The main reason of APPS in SharePoint 2013 is to give Developers the power of creating customizations without full trust access to the target farm, and the sweet reason is you can create apps and publish them in marketplace or corporate app catalog.
This blog series about sharepoint apps will be of different parts and i will try to discuss everything i know here with demonstration. So lets begin:-
APPS the Word(APPS for SharePoint):- You all are familliar with the word app, it was Nokia, Apple then Android who made this word popular in today Techno World, and even a first grade student can explain to you what does an "app" means, Microsoft evolve this in sharepoint from Farm Solutions --> then came SandBox Solutions --> then SharePoint Apps, the reason of this evaluation was mainly to avoid hick ups that admin people feels for Solution Deployment and to avoid effecting SharePoint Farm with custom Solutions or Customizations.
Many of Clients i worked with preffered SharePoint Designer Based customization even though i gave them explanation on how this disturbes the caching and Loading of SharePoint Pages as these have to go through different Parsing mechanism, the only answer they have is Designer based things are easy to modify, change and does not effect our SharePoint Environment.
Yes partially they are right but actually it costs alot to performance and Migration , Upgradation Scenerios.
So i think this evolution of SharePoint Apps are handy but this does not means that Sandbox Solutions are completely Obsolute, Microsoft Says that one should now preffer APPS as much as one can but at situations you have to go with Sandbox Solutions, as we can not modify things on SharePoint Main Sites with Apps
Silly Classification :-
One can classify apps on the basis of Configuration  and hosting model.
Conifguration:- 1) Full Page 2)App Parts 3)UI Command Extension.
Personally if you ask then my favourite is APP Parts but in this part of series we will work with Full Page Apps.
Ahhh i am sorry i should explain you guys first what are these:-
Full-page Based on one or more web pages, these apps include a dedicated UI. You should provide a back button for returning to the parent site, where the app is launched from—but your app will have a UI of its own.Simple as it sounds.. create web pages put javascript on the background yeah and here we go.
App Parts
Also called Client Parts, these render some app content in an IFrame inside pages of the parent site. Usually, App Parts are used to provide users with a small piece of information or functions that can directly interact with the SharePoint user interface.
UI command extension
Used to extend the UI of the parent site, these apps may include a ribbon button or an ECB (Edit Control Block) command to lead the user to a page or function provided by an external app.

Hosting Model Classification

This model relies on a subweb of the parent site (also called an app web) and enables you to use all the common SharePoint artifacts for implementing the UI and the behavior of the SharePoint app. You can take advantage of all the features of SharePoint, such as lists, Web Parts, pages, workflows, and so on.

Apps following this model are hosted on Microsoft Windows Azure, which can access a Microsoft SQL Azure database for managing data, too. The apps are automatically deployed on Windows Azure on your behalf and can communicate with SharePoint through events and the Client Object Model. Secure communication with SharePoint is enforced using OAuth.

From a functional perspective, apps that follow this model are almost the same as autohosted apps. The only difference is that a provider-hosted app has to be deployed on your own hosting environment and does not necessarily use the Windows Azure environment.

Lets Start:-
Ok so lets stop any more discussion and jump on the first app development, I have my development environment ready services required for APPS and Forward lookup Zones for Apps and Service Applications are configured Properly. There are several blogs availlable on how to do this

Ok SO lets begin to develop our very basic and Simple App.

• This going to be a on-premise/sharepoint hosted app.
• Open Visual Studio 2012, create a new project -> Select SharePoint Apps ->;Apps for SharePoint 2013, .Net Framework 4.5 and give a proper name to project (I have given it as KickOff).

• Enter Url of target SharePoint Site & then Change hosting to “SharePoint Hosted” from Autohosted .
• Click Finish and VS 2012 will create a Project for us.
• And this will be what you will get :-

Now let me brief about what we have :-
1. Features Folder:-
 Contains all the features for provisioning contents and capabilities to the target web site, Upon creation this contains only one feature scoped to web-level.

One Major thing to note is you cant modify the scope of this feature and it packages all the contents, the main perpose of this feature is to deploy all the APP contents to the “TARGET APP WEBSITE”.

I would like to add a note here that you should know:-

NOTE:-One has to remember that an app website is provisioned and unprovisioned together with its app. Thus, we create an app that stores content inside its app web, if end user remove or uninstall the app, however the app will be gone also its related data will go away.

2. Package Folder:- Contains the package for deploying the app.
3. Content Folder:- Contains CSS style and a Module to deploy it to the target app.
4. Images Folder:- A Module and Images with default APP Icon image of 96*96 pixel, you can modify this with one of yours.
5. Pages Folder:- Module Feature and the pages of target app contains in this folder, default.aspx is the page contained by default.
6. Scripts Folder:- Represents a Module Feature that is for Javascript Files, APP.js file is the file where we put oue custom scripts(it is our entry point.
7. AppManifest.xml file:- Contains configuration and deployment information related to app.
8. Packages.config file:- Information about the packages referenced by Visual studio project.

Allright now lets just see what happens when out of box feature contained web is deployed to the Site, press F5 and see what happens:-
First Uploading of app starts then installation begins:-

Depending on the kind of environment and configuration installation progresses and takes time

And thus the app will get open:-

You can see there that it does have its default.aspx page loaded and link to go to the site from which it was reffered, in my case "test site" 
If you go back to the Man Site "Test Site in my case" then This app is located under site contents:-
Now Lets Start the Fun :- Make Changes
Open Default.aspx page:-
You will see this :-

Apart from SP.js files it also contains an App.js file reference and this is our target start point of scripting and we will use this to provide our logic.

Now let me just show you a very simple thing, we will create a div and load all site users into it:- so declare a div element in your page with id:- “AppDetails”

And Now lets open" App.js" file and modify the code in it

add two global variables :-

var htmltoappend = ""; //Will store the html string to append in div
var siteUsers; // will store the siteUser object retrieved from CSOM of SharePoint 2013.

This is how the modified APP.js will be:-

We are just initializing siteusers and showing the title of each users and creating a table and loading  this table into the div, just run the app now and see the changes:-

Thanks and coming up next is App Parts and many more exiting Notes about SharePoint Apps....

Friday, October 19, 2012

Custom SharePoint 2010 Ribbon Action for a Specific List Using Visual Studio 2010

Greeting to all my blog readers, we all know how good the sharepoint 2010 Ribbon is, and most wonderfull part is that it is Customizable by using both Visual Studio 2010 and SharePoint Designer 2010.

Recently on Microsoft Technet Forums a person asked this question: "I need a Ribbon Button for a Specific Lists using Visual Studio 2010" as he was thinking to attach Javascript code or CSOM code on that button(not possible with designer way), there was no way he was able to achieve the same using in Elements.xml file.

So i tried my luck with Server Side Object Model to achieve this and later even got the code Client Script object model and Server Side Object Model code to do this. In this blog i am only sharing the way i discovered this in server side object model.
I am showing code written as a Console Application to create a Ribbon Button on Specific List using Visual Studio.

It uses UserCustomActions Collection Property of SPList Object and to add a new UserCustomAction.
The Major Property is:
UserCustomAction.CommandUIExtension, this recieves token from the XML, the same way we enter in the Elements.xml during the traditional way. So here is how my code looks like:-  

Thats it and you will get a Explicit Ribbon button for a Particular List Only...

Thursday, July 19, 2012

SharePoint 2013 is Running at my Home System Now

SP 2013 is at my home now:

It took me three days to make it happen, but yes I have got SP2013 Foundation Preview running on my system.
It is not that tricky that I thought it going to be, actually if we struggled during 2010 and know very well the right ways of installing SharePoint on  a 64 bit environment then it won’t be a big deal this time as we are habitual of certain issues.

So here Is how my first 2013 site  SharePoint foundation site looks like:

My Current System Configuration:

1)Windows Server 2008 R2

2)Sql Server 2008 R2.

3)VS 2012 RC

4)SharePoint Foundation 2013.

How I made it happen:

1)I downloaded SP Foundation from here:

2)Next I Downloaded SP 1 for Windows Server 2008 R2, which is require for SP2013 install from here:

Next I ran the Pre-requisite for SP2013 , if you find any issues with pre-requisite then suggest to follow this blog, which describes awesome powershell scripts to get them all, it helped me too: