A simple JavaScript observable array

Working with JavaScript is very popular in SharePoint enviroment today. Unfortunately, people are looking in other external libraries to achieve functionality they already have, but they are not aware of it. Today, I have decided to present how a SharePoint programmer can make an observable array by using what any web forms based technology already has.
I will take as an example an array containing my names. Initially I will include only two names in it and I will add the other in an observable manner also executing in the same time a handler I will attach to change event.

var arr = ['Andrei', 'Popescu'];

After I have declared my array, is time to make it observable. And of course, as there is no point to make it observable without executing an action when is modified, I will attach a handler to collection change event.

var obsvervableArr = Sys.Observer.makeObservable(arr);
Sys.Observer.addCollectionChanged(obsvervableArr, function(target) {
alert(target);
});

And now, here comes the magic. To add an item to my array in an observable manner, I simply need to call static method “add” of the same Sys.Observable object.

// This will alert my array after new item was added. 
// For complex logic add complex handler to collection changed event
Sys.Observer.add(obsvervableArr,'Vlad');

There are more other method you can use with observable arrays: Sys.Observer.remove, Sys.Observer.removeAt, Sys.Observer.addRange, Sys.Observer.insert and Sys.Observer.clear. All of these are documented on Microsoft website, though not very much details are provided. However, you can use this functionality very easy and create advanced logic, without making use of other libraries. Is all about Microsoft Ajax JavaScript library and it is still the base for SharePoint client side functionality (even on SharePoint 2013).

Advertisements

Reading profile properties in SharePoint 2010

One way to read profile properties in SharePoint 2010 from client side is to consume “userprofileservice.asmx”. Many of the developers created Ajax calls to the service using jQuery or other libraries, which is fine. But there is also an easier to do this. SharePoint 2010 is based on ASP.NET web forms technology and profile service is Ajax enabled, which means we can get the data using only what is already built-in without anything else.

The base of client side web forms is asp:ScriptManager control. It is responsible for loading Microsoft Ajax framework, but not only. Is also able to consume Ajax enabled web services by adding service references to the control.

        <asp:ScriptManager id="ScriptManager" runat="server" enablepagemethods="false" enablepartialrendering="true" enablescriptglobalization="false" enablescriptlocalization="true">
        <Services>
        	<asp:ServiceReference Path="/_vti_bin/userprofileservice.asmx" />
        </Services>
        </asp:ScriptManager>

Following the example above, you add actually a reference to “userprofileservice.asmx”. To be clearer, this is translated into client side by loading a JavaScript file from “/_vti_bin/ userprofileservice.asmx” location. If you analyse the JavaScript file, you can see it contains all the classes you need to work with profiles and the main class is called “Microsoft.Office.Server.UserProfiles.UserProfileService”. And to have an example to start with, I am posting here how you can read a profile.

var service = new Microsoft.Office.Server.UserProfiles.UserProfileService();
service.GetUserProfileByName('DOMAIN\\Account', function(profileData) {
    // Do someething with profileData object
}, function(err) {
    // Alert error message
    alert(err.get_message());
}, null);

Some things I need to mention here. Do not use this method in SharePoint Online. SOAP services are deprecated and there is no guarantees the service will remain there on next updates. However, SharePoint 2010 is an old version and I do not expect the profile service to be removed. So, I would say is safe to use it.

SharePoint HTML 5 controls

Is clear for me, with every technological step in SharePoint environment, Microsoft is getting closer to modern development and HTML 5. And I am talking here about SharePoint:InputFormTextBox control, which is a sort of improved version of classic asp:TextBox control. But let’s what is new in SharePoint Online (most probably in 2013 as well, but I did not test it yet).

Selecting date/date and time

SharePoint:InputFormTextBox can be easily displayed as an HTML 5 date picker control. Is important how do you set text mode property.

<SharePoint:InputFormTextBox runat="server" TextMode="DateTimeLocal"  />

HTML5-calendar
However, being rendered as an HTML 5, is dependent of browser capabilities. In case it is not supported, you will still see a normal text input element.

As you can see, you also have a mask for entering the time. However, there is a simplified version to select only date (in fact is a different control, but please allow my poetic expression :)).

<SharePoint:InputFormTextBox runat="server" TextMode="Date"  />

HTML5-date
In a similar way you can have a control for entering a time value.

<SharePoint:InputFormTextBox runat="server" TextMode="Time"  />

HTML5-time

Range selector control

Range selector control is the second one on my list. Setting text mode to “Range” will do the trick. However, you can also additional HTML 5 range selector control attributes, like min and max value.

<SharePoint:InputFormTextBox runat="server" TextMode="Range" min="0" max="10"  />

HTML5-range

Color picker control

Even is not likely to use this control in an enterprise system, is still there and is a good thing to know you have it available.

<SharePoint:InputFormTextBox runat="server" TextMode="Color"  />

HTML5-color-picker

Number control

Number control can be a real help in developing forms. So having the same syntax and just adjusting the text mode property, you can have one in your page.

<SharePoint:InputFormTextBox runat="server" TextMode="Number" min="1" max="6"  />

As you can see, there is no rocket science to have some server side controls rendering HTML 5 client side elements. However, there is something more there you can do. It seems all of these controls can do postback. For me, it seems SharePoint will become soon a reliable environment for web developers. And I am waiting for the day when all the browsers will have full support HTML 5.

Simulate method overloading in JavaScript

Method overloading in JavaScript is well known technique among the C# developers. However, as popular as it is for server side coders, is not known at all by JavaScript programmers…. And JavaScript become more and more required in SharePoint development.

Let’s assume we have the code below and we are required to perform different action (return different objects types maybe) depending by parameters type:

function overload(param1, param2) {
    
    // Do something if param1 and param2 are numbers

    // Do something else if param1 is string and param2 is missing
}

To achieve this, we might get a little help from SharePoint base library, which is Microsoft Ajax, a very good and old friend for SharePoint Developers. More exactly, this library provides a way to validate parameters in JavaScript. Using Function.validateParameters we can apply different scenarios in our function. Let’s take a look below how:

function overload(param1, param2) {

    // Check if param1 and param2 are numbers
    var e = Function.validateParameters(arguments,[{ name: 'param1', type: Number, mayBeNull: false, optional: false},
                                                   { name: 'param2', type: Number, mayBeNull: false, optional: false }], true);

    // Check if param1 is string and param2 is missing
    var ee = Function.validateParameters(arguments, [{ name: 'param1', type: String, mayBeNull: false, optional: false }], true);

    // Throw an error if parameters are not in expected type
    if (e !== null && ee !== null) {
        throw 'Invalid parameters';
    }

    if(e === null) {
        // Do something if param1 and param2 are numbers
    }

    if( ee === null) {
        // Do something else if param1 is string and param2 is missing
    }
}

Unfortunately documentation is confusing for this function on MSDN. According to the documentation, it should return true if the parameters are validated, otherwise null. In fact it is returning null if parameters are valid and string containing error message if not. Error message is actually generated by another Microsoft Ajax JavaScript object called Error, but this is another discussion.

The example above is simple and does not require additional comments. However, one thing is missing here and this is intellisense. As we are using Microsoft technologies and Visual Studio, we should provide a valid intellisense for it.

function overload(param1, param2) {
    /// <signature>
    ///     <summary>This time param1 and param2 are numbers</summary>
    ///     <param name="param1" type="Number" optional="false" mayBeNull="false">Param 1</param>
    ///     <param name="param2" type="Number" optional="false" mayBeNull="false">Param 2</param> 
    /// </signature>
    /// <signature>
    ///     <summary>This time param1 is string and param2 is not provided</summary>
    ///     <param name="param1" type="String" optional="false" mayBeNull="false">Param 1</param>
    /// </signature>

    // Check if param1 and param2 are numbers
    var e = Function.validateParameters(arguments,[{ name: 'param1', type: Number, mayBeNull: false, optional: false},
                                                   { name: 'param2', type: Number, mayBeNull: false, optional: false }], true);

    // Check if param1 is string and param2 is missing
    var ee = Function.validateParameters(arguments, [{ name: 'param1', type: String, mayBeNull: false, optional: false }], true);

    // Throw an error if parameters are not in expected type
    if (e !== null && ee !== null) {
        throw 'Invalid parameters';
    }

    if(e === null) {
        // Do something if param1 and param2 are numbers
    }

    if( ee === null) {
        // Do something else if param1 is string and param2 is missing
    }
}

Providing XML comments on the beginning of the function will enable Visual Studio intellisense, showing information about both signatures. I was not able to provide a screenshot, but if you try yourself you will know I am talking about.

Hoping this will help you to organize your JavaScript code better, the last thing I need to say is “Happy Coding”.

Creating a custom form in SharePoint Online

Once again, SharePoint Online prove it is an interesting tool and, more important, it doesn’t necessary leave behind old technologies, as most developers are thinking. If developers are thinking old custom forms are dead, they might be wrong, as Microsoft provides now an easier method to create them. We will consider here creation of a custom new form in SharePoint Online.

Open the site in SharePoint Designer, navigate to lists, right click on the specified and you will see properties window. In forms section, there is a “New” button you need to click.
formsponline
You need to click on need to see the window where you enter the details for the new custom form.
CreateNewForm
And now, if you open the new created page in SharePoint Designer you will see the big surprize: IT IS A DATAFORMWEBART. This means you can still do XSLT customization. So you can still develop forms using technology you already know.

Execute function when page loads in SharePoint

I have been working with SharePoint for five years and most of these years were dedicated to JavaScript development in SharePoint. But even after five years, I keep seeing developers making a big mix of code, especially when it comes to execute JavaScript functions when the page is loaded.

As jQuery is very popular today, most of the developers are using $(document).ready() for executing code when page is fully loaded. I am not going to explain this technique, but I am going to tell it is not perfect. And there is a big reason for this. It is not executed when an asynchronous postback occurred.

There is a solution for this and is very simple. Creating a simple function called “pageLoad” and put the logic there should solve the problem, as this function is trigger by the Microsoft Ajax.

function pageLoad(sender,args) {
// This function is executed when page is loaded and even if async postback occured.
}

Of course, different logic can be applied if page is loaded after asynchronous or not (maybe an initial load).

function pageLoad(sender, args) {
    var isAsyncLoad = args.get_isPartialLoad();
    // Split the logic if load is sync or async
}

Handlers for load event can be added also programmatically.

function a(sender, args) {
	alert(sender.get_isInAsyncPostBack());
}

function b(sender, args) {
	alert(sender.get_isInAsyncPostBack());
}

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(a);
prm.add_pageLoaded(b);

In total, there are several events which can be used with Sys.WebForms.PageRequestManager, but these will be treated in a different post: initializeRequest, beginRequest, pageLoading,pageLoaded, endRequest.

However, if all of the above code is working, is because SharePoint is web forms technology based, but there is also another way to do this, this time SharePoint specific. The technique is simple and consists in adding function names to an array called “_spBodyOnLoadFunctionNames”.

function a() {
	alert('a');
}

function b() {
	alert('b');
}

_spBodyOnLoadFunctionNames.push('a');
_spBodyOnLoadFunctionNames.push('b');

Using this method, event handler will be trigger only if load is complete (no function executed after partial postback). This is the reason I personally prefer the first ones.

So here we are at the end of the article. If you feel you need to add something, please let me know. I might missed some information.

Happy Coding!!! 🙂

Playing with “this” keyword in JavaScript

Understanding “this” keyword and how to play with it is a very important thing in JavaScript. In general, “this” is referencing to current instance, similar with C#. However, I will try to illustrate in some example, what “this” means.

“this” referencing to window object

This is the classical JavaScript example, when “this” keyword is referencing to window object.

        var name = 'Popescu';       

        function randomFunction() {
            alert(this.name);
        }

        // Will alert Popescu
        randomFunction();

To understand this example, you need to know that window is object, name is a property of window and randomMethod is a method of it. As name and property are properties of the same object, variable “name”, referencing inside the method using “this.name”, represents the output of the alert.

Specify “this” reference using call and apply

Classical example above is not necessary to be always true. A JavaScript developer can specify what “this” should reference by using call and apply. Let’s take a look on below portion of the code.

  var name = 'Popescu';

var context = new Object();
context.name = 'Popescu Andrei Vlad';

function randomFunction() {
   alert(this.name);
}

// Will alert Popescu Andrei Vlad
randomFunction.call(context);
randomFunction.apply(context);

This time “this” is referencing to context object. And if you are a fan of Microsoft Ajax, you can write it even more beautiful.

var name = 'Popescu';

var context = new Object();
context.name = 'Popescu Andrei Vlad';

function randomFunction() {
    alert(this.name);
}

// Will alert Popescu Andrei Vlad
Function.createDelegate(context, randomFunction)();

“this” in a XMLHttpRequest context

Using “this” in a XmlHttpRequest context can create confusion for a beginner. For example, code below will alert undefined.

var name = 'Popescu';

var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', 'url', true);
xmlHttp.send(null);

xmlHttp.onreadystatechange = function () {
    alert(this.name);
}

This is because, in our code “this” is not referencing any more to window object. It is a reference to XMLHttpRequest object. So, alerting value of this.readyState will work.